I have follo开发者_高级运维wing 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.
$("#txtBoxID").keypress(function (event) {
var reg = /[\d\.]/g;
if (!reg.test((event.key))) {
return false;
}
});
I have done like above, I have used keypress and its event and one regular function which will allow user to enter only DIGITS in text box/ input box.
You can check event.key , which give value of key has bee
精彩评论