user2181397 user2181397 - 2 years ago 61
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

attribute is updating, but it is not reflecting in the view.

Here is my code


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


var getCheckBox = $("#paid-change");

function check(){
function uncheck(){

// check/uncheck in every 2 seconds
switch (getCheckBox.val()){ //get checkbox value
case "0":
check() // if value is 0 check it
case "1":
uncheck() //uncheck it


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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download