Cancel jQuery keypress

It is possible (compatible with cross-browser) with CANCEL keystroke after the user has done this (for example, in a text box)

The code I use changes the value of the text field after pressing the key:

$('.number').keypress(function() { this.value = this.value.replace(/[^0-9\.]/g, ''); }); 
+6
javascript jquery textbox keypress keystroke
source share
2 answers

SOLVED (AND UPDATED)

Sorry, I did not test the most obvious option - which worked:

 $('.number').keypress(function(event) { return /[0-9\.]/.test(String.fromCharCode(event.keyCode)); }); 
+4
source share
 $('.number').keypress(function() { if ( this.value == 'foobar' ){ // "Cancel" keystroke return false; } this.value = this.value.replace(/[^0-9\.]/g, ''); }); 
+4
source share

All Articles