user2181397 user2181397 - 5 months ago 9
Javascript Question

Checkbox is not checking though attribute values are updating

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
attribute is updating, but it is not reflecting in the view.

Here is my code

HTML

<input type="checkbox" name="paid" id="paid-change" value = "1">


JS

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)


Here is a jsfiddle.

Inspecting the element,you the attributes are updating but not reflecting on the view.

Any idea where I am making mistake?

Answer

Instead of attr() to set checked attribute, use prop().

getCheckBox.prop('checked', true);

Updated Fiddle


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

Fiddle Demo