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
The best way is to check value of input, instead of pressed key. Because there are tabs, arrows, backspace and other characters that need to be checked when You use character code.
That code check input value after user pressed a key:
$('#p_first').keyup(function(){
while(! /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/.test($('#p_first').val())){
$('#p_first').val($('#p_first').val().slice(0, -1));
}
});
While loop remove last character until input value is valid. Regex /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/ validate integer and float number eg. "12,12", "12.1", "12.". It is important that number "12." (dot at the end) also be valid! Otherwise user can't enter any period.
And then on submit regex check for valid float number ([0-9]{1,2}) instead of ([0-9]{0,2}):
$('form').submit(function(e){
if(! /^([0-9]+)((\.|,)([0-9]{1,2}))?$/.test($('#p_first').val())){
$('#p_first').addClass('error');
e.preventDefault();
}
});
Notice: It is better to assign $('#p_first') into variable. var input = $('#p_first');
Try This..it may usefull.
<HTML>
<input type="text" name="qty" id="price" value="" style="width:100px;" field="Quantity" class="required">
</HTML>
<script>
$(document).ready(function() {
$('#price').live('keyup',function(){
this.value = this.value.replace(/[^0-9\.]/g,'');
});
});
</script>
I decided to use the answer provided by @Rahul Yadav, but it is erroneous since it doesn't consider num pad keys, which have different codes.
Here, you can see a excerpt of the code table:
Here the function I implemented:
function isNumberKey(e) {
var result = false;
try {
var charCode = (e.which) ? e.which : e.keyCode;
if ((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) {
result = true;
}
}
catch(err) {
//console.log(err);
}
return result;
}
With a key event, use event.key to get the actual value. To check if integer:
isFinite(event.key);
An easier HTML solution would be to use the number type input. It restricts to only numbers (kind of).
<input type="number">
Either way, you should clean all user input with:
string.replace(/[^0-9]/g,'');
Try this solution:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Demo: http://jsfiddle.net/DbRTj/
Same questions:
Try binding to the keypress event instead of keyup. It gets fired repeatedly when a key is held down. When the key pressed is not a number you can call preventDefault() which will keep the key from being placed in the input tag.
$('#p_first').keypress(function(event){
if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
});
Working Example: http://jsfiddle.net/rTWrb/2/