简体   繁体   中英

Limit input text boxes to just 0 or 1

I wrote this little script that checks to see that the user entered a 0 or a 1. If its anything else, it changes it to a 0:

$('.lcdnum1').keyup(function(){
    if (!($(this).val()==='0' || $(this).val()==='1')){
        $(this).val('0');
    }
});

The only thing I don't like about it, is that you see the "bad" character first. If you type a "x", it briefly shows the "x", then it goes away and is replaced by a 0.

Here is my test URL that demonstrates what is happening: http://sterlingmodular.com/test/plan-series-build.asp?console=PLNUno&woodtrim=TOBA&speakerplatform=SPSA&lcd4=1

How can I modify this so that its a little smoother for the user? Ie, the "bad" character shouldn't show in the first place. Thank you!

Try using .keydown:

http://api.jquery.com/keydown/

Keyup waits until the user release the key from their keyboard which will give you a split second of input.

Just make a little adjustment to the event you are using, you are using keyup which means after the key has been released it will run the check. However if you run the check before the key is released you will get the desired outcome.

$('.lcdnum1').keydown(function(){
    if (!($(this).val()==='0' || $(this).val()==='1')){
        $(this).val('0');
    }
});
$('.lcdnum1').keyup(function(){
    var value = $.trim(this.value);
    if (value != '1' ){
        $(this).val('0');
    }
});

DEMO

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