Reputation: 10831
When typing into a <input type="text">
field I would like to precheck every entered value before it appears on the screen. E.g. if the user enters any non numeric value, nothing will happen and only if he enters a numeric value the field will change.
Which is the right event to use keydown()
, keyup()
or is there something better? How do I cancel the current change of the text field without having to remember the old value and manually resetting it?
Upvotes: 3
Views: 206
Reputation: 165961
You could bind to the keypress
event and then check the character represented by the which
property of the event object. If it isn't a number you can use preventDefault
to prevent the default behaviour of writing the character to the element:
$("#someInput").keypress(function(e) {
if(isNaN(String.fromCharCode(e.which))) {
e.preventDefault();
}
});
Here's a working example.
Upvotes: 3