首页 > 解决方案 > 如果所有字段都用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">

标签: javascriptjquery

解决方案


要在没有显式循环的情况下实现这一点,您可以使用它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">


推荐阅读