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?
You could bind to the
keypressevent and then check the character represented by thewhichproperty of the event object. If it isn’t a number you can usepreventDefaultto prevent the default behaviour of writing the character to the element:Here’s a working example.