user291701
user291701

Reputation: 39731

Block some characters from being typed in a text box?

I'd like to block users from typing certain characters in a text box (want to only allow [a-z], [A-Z], and underscore). I took this from a previous Q, but if I press the arrow keys (in FF 3.6), I get a js error:

"window.event is undefined"

this is the original code, what can I change window.event to in this case?:

$("#myTextBox").bind("keypress", function(event) { 
    var charCode = (event.which) ? event.which : window.event.keyCode;  
    if (charCode <= 13) { 
        return true; 
    } 
    else { 
        var keyChar = String.fromCharCode(charCode); 
        var re = /[a-zA-Z_]/ 
        return re.test(keyChar); 
    }
});

Thanks

Upvotes: 1

Views: 6174

Answers (3)

Vindicated
Vindicated

Reputation: 21

Just remove the window because your event is defined in jQuery ($)

Upvotes: 0

nickf
nickf

Reputation: 546473

I'm not sure if it'll be right for you, but perhaps you might want to use the Masked Input Plugin?

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630607

You can do just this:

$("#myTextBox").bind("keypress", function(event) { 
    var charCode = event.which;
    if (charCode <= 13) return true; 

    var keyChar = String.fromCharCode(charCode); 
    return /[a-zA-Z_]/.test(keyChar); 
});​

jQuery normalizes event.which already...and you can test it here :)

If it didn't, the fix would just be event.keyCode, you want to refer to the event passed as the parameter to this function, not a property on window. In this case, if the if condition was true, it'd return...so there's no need for an if/else, you can simplify it like I have above.

Upvotes: 9

Related Questions