如何解决不需要字段时自动聚焦于每个文本框
我有一个包含多个文本框的页面,这些文本框都不是必填字段(即用户可以填写所需的任意数量)。但是,我无法从第二个文本框开始自动对焦,而是当我按Enter键移到下一个文本框时提交表单(这可能是因为不需要输入)。有没有一种方法可以使我在键入上一个文本框的响应后即使在不需要该字段的情况下也可以自动聚焦到下一个文本框/停止提交表单?感谢您的帮助!
<html>
<main>
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus ></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" ></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" ></br>
<br><input type="text" id="response4" name="response4" autocomplete="off" > </br>
<button type="submit">Submit</button>
</form>
</main>
</html>
解决方法
尝试执行此操作,它应该使Enter仅在最后一个输入上提交,而其他时候,它仅移至下一个输入。
别忘了将onkeydown添加到除最后一个输入之外的所有输入中。
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus onkeydown="next(this,event)"></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" onkeydown="next(this,event)"></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" onkeydown="next(this,event)"></br>
<br><input type="text" id="response4" name="response4" autocomplete="off"> </br>
<button type="submit">Submit</button>
</form>
<script>
function next(currElement,e) {
if (e.keyCode === 13) {
e.preventDefault();
let nextNum = parseInt(currElement.id.substr(8)) + 1;
document.getElementById('response' + nextNum).focus();
return false;
}
}
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。