I have a checkbox which I want to check/uncheck using setInterval in every 2 secs.
But it is getting checked/unchecked only once.
Also when I am inspecting the DOM , I can see it's value and
checked
<input type="checkbox" name="paid" id="paid-change" value = "1">
var getCheckBox = $("#paid-change");
function check(){
getCheckBox.attr('checked',true);
getCheckBox.val("1")
}
function uncheck(){
getCheckBox.attr('checked',false);
getCheckBox.val("0")
}
// check/uncheck in every 2 seconds
setInterval(function(){
switch (getCheckBox.val()){ //get checkbox value
case "0":
check() // if value is 0 check it
break;
case "1":
uncheck() //uncheck it
break;
}
},2000)
Instead of attr()
to set checked
attribute, use prop()
.
getCheckBox.prop('checked', true);
The code can be rewritten as
// Cache checkbox object
var checkbox = $("#paid-change");
// Function to toggle the checkbox value and state
function toggleCheckbox() {
// Change the 'checked' property
checkbox.prop('checked', function(i, checked) {
return !checked; // Invert the checked status
}).val(function(i, val) {
return +this.checked; // Change the value
});
}
setInterval(toggleCheckbox, 2000); // Call the function after each 2 seconds