views:

77

answers:

2

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, '');
});
+3  A: 
$('.number').keypress(function() {
    if ( this.value == 'foobar' ){
        // "Cancel" keystroke
        return false;
    }
    this.value = this.value.replace(/[^0-9\.]/g, '');
});
PetersenDidIt
This wouldn't work. You would need to test for prohibited values in `this.value` using a regular expression. You're testing for an exact match against the entirety of `this.value`
patrick dw
Actually, if the `if()` statement ever did return `true`, the `replace()` wouldn't fire. Since you're testing against `this.value`, that is a crucial part.
patrick dw
+2  A: 

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));
});
Jimbo
+1 This is the way to do it if you don't want to briefly see the prohibited entry. You could clean it up a little using `test()`, like this: `/[^0-9\.]/.test(String.fromCharCode(event.keyCode))`. No replace or assignment is needed since you are doing `return false;`. No need for the `g` global identifier either, since you're testing a single key event.
patrick dw
Thanks, I have updated my answer with your suggestion with one small change - removing the carrat (^) from the regex as that would invert the result of the test :) Much appreciated!
Jimbo