Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel a keystroke in jQuery

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, '');
});
like image 431
Jimbo Avatar asked May 31 '10 15:05

Jimbo


People also ask

How do I turn off keypress events?

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(); });

How do I stop enter key?

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.

What is Keyup and Keydown in jQuery?

Definition and Usagekeydown - The key is on its way down. keypress - The key is pressed down. keyup - The key is released.


2 Answers

$('.number').keypress(function() {
    if ( this.value == 'foobar' ){
        // "Cancel" keystroke
        return false;
    }
    this.value = this.value.replace(/[^0-9\.]/g, '');
});
like image 129
PetersenDidIt Avatar answered Oct 13 '22 20:10

PetersenDidIt


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));
});
like image 4
Jimbo Avatar answered Oct 13 '22 20:10

Jimbo