I have following code snippet:
var reg = /^[0-9]$/;
$('input[type="text"]').keypress(function(){
console.log(reg.test(parseInt($(this).val())));
});
When I press any key (digit or other) it always return false. But I can't find out the problem.Please give me some solutions.
See How to allow only numeric (0-9) in HTML inputbox using jQuery? for a proper solution.
In case you want to do something own, have a look at those plugins anyway. It's very important to not break common things like backspace (or ctrl+c/v/x) as users usually expect those keys to work.
The regex you've created tests for exactly 1 occurance of any digit. It also asserts that it's the begining of the string followed by a single digit, then the end of string.
The keypress event is triggered before actual content is put into the textbox. This should only work for the second key press, because that's when the textbox content .val() yields exactly 1 digit.
If you follow the link posted by @ThiefMaster you'll find the answer to your question. You'll also note that it's using the charCode and keyCode properties of the event object to do validation not the contents of the textbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With