[英]Submit form on checkbox change delay
Goal: I have a form with checkboxes that I want to submit on their .change() event. 目标:我有一个带有复选框的表单,我想在其.change()事件上提交该表单。 I want there to be a delay before submitting that is reset each time another checkbox is clicked.
我希望在提交之前有一个延迟,每次单击另一个复选框时都会将其重置。
Code: 码:
$('input[type="checkbox"]').change(function(){
setTimeout(function(){
$('#nav_form').submit();
},750);
});
This code works but submits form too soon. 此代码有效,但提交表单的时间过早。 And if I set the milliseconds to a higher value like a few seconds, it kinda works if users select many checkboxes but when they select just 1 or 2, the delay is really obvious.
而且,如果我将毫秒设置为更高的值(例如几秒钟),那么如果用户选择了许多复选框,那还是可以的,但是当他们仅选择1或2时,延迟确实很明显。
Thanks in advance for all the help! 在此先感谢您提供的所有帮助!
You need to clear the setTimeout - it is comparable to "debouncing" text entry in for example an Ajax controlled autocomplete. 您需要清除setTimeout-它类似于“反跳”文本条目,例如在Ajax控制的自动完成中。
var tId;
$('input[type="checkbox"]').change(function(){
clearTimeout(tId);
tId=setTimeout(function(){
$('#nav_form').submit();
},750);
});
You may want to add a test if you only want to submit checked boxes: 如果您只想提交复选框,则可能要添加测试:
var tId;
$('input[type="checkbox"]').change(function(){
clearTimeout(tId);
if (('input[type="checkbox"]:checked').length>0){
tId=setTimeout(function(){
$('#nav_form').submit();
},750);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.