I want to make an input text numeric only or no base on a user selection from a dropdown (if the user choose Customer Code or Rate Request Id then the textbox is numeric only, if it is Customer Code can write letters). Here is the code that I wrote but is not working, any help? jsfiddle code
<select id="test" class="target">
<option value="custName">Customer Name</option>
<option value="custCode">Customer Code</option>
<option value="rateReqId">Rate Request Id</option>
</select>
<input id="target" type="text" />
and the Javascript code is:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function() {
return this.each(function() {
$(this).keydown(function(e) {
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
});
};
$('#test').change(function() {
var val = this.value;
switch (val) {
case "custName":
$("#target").unbind('ForceNumericOnly')
break;
case "custCode":
alert('inside custCode');
$("#target").ForceNumericOnly();
break;
case "rateReqId":
break;
default:
}
});
thanks to @thecodeparadox I ended doing the following: demo
html code:
<select id="test" class="target">
<option value="custName">Customer Name</option>
<option value="custCode">Customer Code</option>
<option value="rateReqId">Rate Request Id</option>
</select>
<input id="target" type="text" />
<div id="toolTip" style="border: solid 1px #000; padding: 2px 2px 2px 2px; background-color: #f1f1f1; width: 150px; height: 30px; font-size: 11px; position: absolute; top: 250px;
left: 130px; display: none;">test
</div>
jquery code:
// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function(selectedFilter) {
return this.each(function() {
$(this).keydown(function(e) {
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
var result = (
key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
if (!result) {
var tooltip = $('#toolTip');
if (!tooltip.is(':visible')) {
tooltip.text("Numeric values only for " + selectedFilter);
tooltip.show().fadeOut(3000);
}
}
return result;
});
});
};
$('#test').change(function() {
var val = this.value;
var input = $("#target");
switch (val) {
case "custName":
input.val('').unbind();
break;
case "custCode":
input.val('').unbind().ForceNumericOnly("Customer Code");
break;
case "rateReqId":
input.val('').unbind().ForceNumericOnly("Rate Request Id");
break;
default:
}
});
Actually I dont know if this is the better way to do it or the most effective one, so still open to suggestions
Thanks for the help :)