开发者

Block some characters from being typed in a text box?

开发者 https://www.devze.com 2023-01-06 05:16 出处:网络
开发者_如何转开发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 (
开发者_如何转开发

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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消