简体   繁体   中英

How to specify which characters are allowed in a textbox with jQuery?

http://jsfiddle.net/WhP8q/

I'm trying to restrict input to alpha numeric, 0-9, AZ,az.

The ASCII table i'm referencing: http://www.asciitable.com/ Here is what I have so far

$(function() {
    $("input").bind("keydown paste", function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        var c = code;
        var letterAllowed = ((c > 47 && c < 58) || (c > 64 && c < 90) || (c > 96 && c < 123))
        if (code > 32 && !letterAllowed) {
            return false;
        }
    });
});​

right now, the tilde (~) character is prevented from getting input into the field, but other special / shift characters such as !@#$% all get entered into the text field. I'm pretty sure my logic is sound, but my issue is with some misunderstanding of javascript bindings? idk

Preventing character input for only some cases is very complicated in javascript, as in the keypress event (the one you'd want to prevent) you do not know the afterwards value of your input, but only the keycode of the pressed key (and not even the resulting char for sure). Also, you will need to care about special keys like or .

I'd recommend something like this:

$("input").on("keypress keyup paste", function(e) {
    this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
});

In case of restrict the character you enter, You can replace the character which is not alphanumberic.

<input type='text' id="txtAlphaNumeric"/>
<input type='text' id="txtNumeric"/>
<input type='text' id="txtAlphabet"/>
<script type="text/javascript">
$(function() {
    $('#txtNumeric').keyup(function() {
        if (this.value.match(/[^0-9]/g)) {
            this.value = this.value.replace(/[^0-9]/g, '');
        }
    });
    $('#txtAlphabet').keyup(function() {
        if (this.value.match(/[^a-zA-Z]/g)) {
            this.value = this.value.replace(/[^a-zA-Z]/g, '');
        }
    });
    $('#txtAlphaNumeric').keyup(function() {
        if (this.value.match(/[^a-zA-Z0-9]/g)) {
            this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
        }
    });
});
</script>

Answer taken from: jquery allow only alphanumeric

Turns out, I need to do the following:

$("input").keypress(function(e){
        var code = e.charCode;

charCode will give the actual character code of the typed letter, rather than the ascii code of the last pressed key

see http://api.jquery.com/keypress/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM