我看到很多用于更改最大长度输入文本字段焦点的脚本,但我似乎找不到任何在当前字段中的文本达到特定字符时将光标移动到下一个字段的脚本。我需要这个的原因是因为输入会有不同的长度,所以不能使用最大长度。例如,我将输入 abcd1234!。感叹号 (!) 将是脚本将焦点切换到下一个字段的键。我正在使用以下脚本生成我的文本字段。
<div id="myDiv">
<input type="text" name="qr[]" id="txt_1" autofocus />
</div>
<script>
$('#myDiv').on('keyup', 'input', function() {
if($(this).val() == ''){
$(this).next().remove();
return;
}
else if($(this).next().val() == '') {
console.log('here');
return;
}
var newTxt = $(this).clone();
var id = newTxt.attr('id');
newTxt.attr('id', 'txt_' + (parseInt(id.substring(id.indexOf('_') + 1))));
newTxt.val('');
$(this).parent().append(newTxt);
});
</script>
最佳答案
这是一个 JSFiddle 这就是你想要的。
$('#myDiv').on('keyup', 'input', function (e) {
if ($(this).val() == '') {
$(this).next().remove();
return;
} else if ($(this).next().val() == '') {
if (e.keyCode === 49 && e.shiftKey) {
$(this).next().focus();
}
return;
}
var newTxt = $(this).clone();
var id = newTxt.attr('id');
newTxt.attr('id', 'txt_' + (parseInt(id.substring(id.indexOf('_') + 1))));
newTxt.val('');
$(this).parent().append(newTxt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="myDiv">
<input type="text" name="qr[]" id="txt_1" autofocus />
</div>
基本上,我正在检查事件(函数中的第一个参数)是否为键代码 49(1)键以及 Shift 键被按下。然后我关注下一个元素。
关于javascript - 当输入的字符串到达特定字符时,jQuery 将焦点更改为下一个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31196456/