javascript - 如果所有字段都用jQuery填写而不使用each(),如何自动提交表单?
问题描述
如果填写了所有输入字段,我已经制作了一个 OTP 表单,我想通过 AJAX 提交该表单。是否可以使用类选择器$(".tp")
?
$(document).ready(function() {
$(".tp").keyup(function() {
if (this.value.length == 1) {
// this will automatically change the focus as soon as an input is done
$(this).next().focus()
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
解决方案
要在没有显式循环的情况下实现这一点,您可以使用它filter()
来查找所有没有值的字段。如果没有,那么您知道您可以安全地发出 AJAX 请求。尝试这个:
jQuery($ => {
let $tp = $(".tp").on('input', e => {
if (e.target.value.length == 1) {
$(e.target).next().focus();
}
if ($tp.filter((i, el) => !el.value.trim()).length == 0) {
console.log('AJAX call goes here...');
}
});
});
input {
width: 15px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
<input type="tel" class="tp" maxlength="1">
推荐阅读
- xpath - 多个属性中单个属性的 CSS 选择器
- c - c99 -- 返回前的预期表达式
- javascript - 引导模式复制内容直到刷新
- c++ - 优先队列构造函数的作用
- computer-science - 如何设计 NPDA 来接受这些语言?
- javascript - JavaScript - 导入后 (webmix) 未捕获 ReferenceError: getJobData is not defined 错误
- node.js - 是否可以在控制台中一键重启我的 DIScordBot?
- python - 如何将列表文本中的数字与字母分开
- python-3.x - 分离 Tkinter GUI 和应用程序的控制
- java - 如何对 API 进行单元测试?