原谅任何不良编码。
我正在尝试编码一种表单,当用户命中" Enter"并且它们位于文本框之一中时,他们将继续进行下一个文本框,而不是提交表单。我有一部分代码可以为此工作,除非禁用了一个文本框(属性'disabled'='disabled'),它将简单地停止并且不会超越它。
我希望它跳过残障的文本框,然后转到下一个。
这是我的工作代码(在禁用的文本框上命中并贴上粘贴)。我很尴尬地发布了我为完成这项工作的尝试: - |
$('input').keydown(function (e) {
var ae = document.activeElement;
if (
ae.type != "button" &&
ae.type != "submit" &&
ae.type != "password"
)
{
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 13) {
e.preventDefault();
var inputs = $('form').find('input:visible');
inputs.eq(inputs.index(this) + 1).focus();
}
}
});
一种称赞@nino filiu
的jQuery解决方案var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (key == 13) {
e.preventDefault();
var inputs = $('form').find('input:enabled'); //inputs are disabled not hidden
inputs.eq(inputs.index(this) + 1).focus();
}
更改是在input:enabled
而不是input:visible
中。后者会发现任何没有隐藏的输入,前者会找到任何未禁用的输入
您去这里。不需要jQuery。我希望该代码能够说明自己,但我很乐意在需要时详细解释。
帕特里克·罗伯茨(Patrick Roberts)提出的一项建议,使用Shift+Enter
跳到以前的输入:
const inputs = Array.from(document.querySelectorAll('input'));
const enabledInputs = Array.from(document.querySelectorAll('input:enabled'));
inputs.forEach(elt => {
elt.addEventListener('keydown', evt => {
if (evt.key=='Enter') {
let currentInputIndex = enabledInputs.indexOf(elt);
let nextInputIndex;
if (evt.shiftKey) {
nextInputIndex = (currentInputIndex-1)%enabledInputs.length;
} else {
nextInputIndex = (currentInputIndex+1)%enabledInputs.length;
}
enabledInputs[nextInputIndex].focus();
}
})
})
input {
display: block;
}
<input>
<input>
<input disabled>
<input>
<input>
<input disabled>
<input>
<input>