简体   繁体   English

将输入文本框限制为0或1

[英]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: 我写了这个小脚本,检查用户是否输入了0或1。如果还有其他内容,它将更改为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. 如果键入“ x”,它会短暂显示“ x”,然后消失并被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 这是我的测试URL,它演示了正在发生的事情: 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: 尝试使用.keydown:

http://api.jquery.com/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. 只需对正在使用的事件进行一点调整,即您正在使用keyup,这意味着在释放密钥之后它将运行检查。 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 DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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