Goal: I have a form with checkboxes that I want to submit on their .change() event. 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.
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.
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);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.