如果可以在 JQuery 按键事件中仅允许输入框中的某些文本
If it is Possible to allow only certain text in input box in JQuery keypress event
如果可以在相同的 keyPress 事件中允许输入框中的特定字符串 order.Important 事情是我只需要以相同的顺序允许。
示例:如果我需要允许 "NILL" 用户必须输入相同的 order.If 用户输入 "NL" 那么我们需要限制 them.If 可能。
我试过以下方法:
$("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" />
您可以将字符串转换为字符数组,然后检查每个索引是否与输入的键匹配
$(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" />
如果可以在相同的 keyPress 事件中允许输入框中的特定字符串 order.Important 事情是我只需要以相同的顺序允许。
示例:如果我需要允许 "NILL" 用户必须输入相同的 order.If 用户输入 "NL" 那么我们需要限制 them.If 可能。
我试过以下方法:
$("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" />
您可以将字符串转换为字符数组,然后检查每个索引是否与输入的键匹配
$(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" />