[英]Javascript: Jump to next enabled text box on [enter]
原谅任何错误的编码。
我正在尝试编写一个表单,在该表单中,当用户单击“ 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();
}
}
});
干得好。 不需要jQuery。 我希望代码能说明一切,但是如果需要,我很乐于详细解释它。
除了OP的请求外, 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>
一个赞美@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
。 后者将找到任何未隐藏的输入,前者将找到未禁用的任何输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.