Is is possible (cross-browser compatible) to CANCEL a keystroke after a user has made it (for example on a textbox)
The code I currently use edits the textbox value after the keystroke has been displayed:
$('.number').keypress(function() {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
How do I turn off keypress events? Alternatively, you could attach another event handler to the input field, and in this handler stop the propagation of the event: jQuery('#input-field-id'). bind('keypress', function(e) { e. stopPropagation(); });
To prevent this from happening you can simply stop the form being submitted if the enter key had been pressed. This is done by binding a JQuery event to the input elements of the form and returning false if the key pressed is enter, which has the keyCode value of 13.
Definition and Usagekeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.
$('.number').keypress(function() {
if ( this.value == 'foobar' ){
// "Cancel" keystroke
return false;
}
this.value = this.value.replace(/[^0-9\.]/g, '');
});
SOLVED (AND UPDATED)
Apologies, I didnt test the most obvious option - which worked:
$('.number').keypress(function(event) {
return /[0-9\.]/.test(String.fromCharCode(event.keyCode));
});
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