i am trying to create an input field where the user can only type in numbers. this function is already working almost fine for me:
$(\'#p_first\').k
I used the following function to check if a given string is number or not. This implementation works on keyup and keydown and also takes care of numpad keys
// Validate Numeric inputs
function isNumber(o) {
return o == '' || !isNaN(o - 0);
}
Assuming that your key code on the keyup or keydown event is in keyCode variable:
var keyCode = e.keyCode || e.which;
if (keyCode >= 96 && keyCode <= 105) {
// Numpad keys
keyCode -= 48;
}
console.log(isNumber(String.fromCharCode(keyCode)));
console.log(isNumber($(this).val() + String.fromCharCode(keyCode)));
Return false if the return value from isNumber is false:
var txtVal = $(this).val() + String.fromCharCode(keyCode);
if (!isNumber(txtVal)) {
e.returnValue = false;
}
JavaScript:
function isNumberKey(a){
var x=a.val();
a.val(x.replace(/[^0-9\.]/g,''));
}
HTML:
<td><input type="text" name="qty" onkeypress="onkeyup="return isNumberKey($(this));"" value="" style="width:100px;" field="Quantity" class="required"></td>