【问题标题】:If it is Possible to allow only certain text in input box in JQuery keypress event [closed]如果可以在 JQuery 按键事件的输入框中仅允许某些文本[关闭]
【发布时间】:2019-02-09 13:23:57
【问题描述】:

如果可以在 keyPress 事件的输入框中以相同的顺序允许特定的字符串。重要的是我只需要以相同的顺序允许。

示例:如果我需要允许“NILL”用户必须以相同的顺序输入。如果用户输入“NL”,那么我们需要限制它们。如果可能的话。

我尝试了以下方法:

$("input").keypress(function(e) {
    var chr = chr = e.key;
    if ("NILL".indexOf(chr) < 0 && e.which != 13)
        return false;
        console.log('allowed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo" />

【问题讨论】:

  • 是的,这是可能的。你已经尝试过什么?
  • 我在问题中编辑我的代码。(添加代码)请立即查看
  • 使用chr = e.key获取键值作为字符
  • @CalvinNunes 更新
  • 我不确定这个问题有什么问题,以获得更多的反对票。 :(

标签: javascript jquery validation keypress


【解决方案1】:

您可以将字符串转换为字符数组,然后检查每个索引是否与输入的键匹配

$(document).ready(function(){

var restriction = "NILL";
restriction = restriction.split(''); // transform to array of char
$("input").keypress(function(e) {
    var chr = e.key.toUpperCase();
    if(restriction[$(this).val().length] != chr){
    return false;
    }
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo" />

【讨论】:

  • 谢谢,它工作:)
猜你喜欢
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
相关资源
最近更新 更多