[英]How to automatically submit a form if all fields are filled in jQuery without using each()?
I have made a OTP form which I want to submit via AJAX if all it's input fields are filled in. Is it possible with using class selector $(".tp")
?我已经制作了一个 OTP 表单,如果它的所有输入字段都已填写,我想通过 AJAX 提交。是否可以使用 class 选择器
$(".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">
To achieve this without an explicit loop you can use filter()
to find all fields which do not have a value.要在没有显式循环的情况下实现这一点,您可以使用
filter()
来查找所有没有值的字段。 If there aren't any, then you know you are safe to make your AJAX request.如果没有,那么您知道您可以安全地提出 AJAX 请求。 Try this:
尝试这个:
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">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.