Jimbo
Jimbo

Reputation: 22964

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, '');
});

Upvotes: 6

Views: 1058

Answers (2)

Jimbo
Jimbo

Reputation: 22964

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

Upvotes: 4

PetersenDidIt
PetersenDidIt

Reputation: 25620

$('.number').keypress(function() {
    if ( this.value == 'foobar' ){
        // "Cancel" keystroke
        return false;
    }
    this.value = this.value.replace(/[^0-9\.]/g, '');
});

Upvotes: 4

Related Questions