javascript - Checkbox is not checking though attribute values are updating -


i have checkbox want check/uncheck using setinterval in every 2 secs.

but getting checked/unchecked once.

also when inspecting dom , can see it's value , checked attribute updating, not reflecting in view.

here 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 0 check      break;  case "1":      uncheck() //uncheck      break; }  },2000) 

here jsfiddle.

inspecting element,you attributes updating not reflecting on view.

any idea making mistake?

instead of attr() set checked attribute, use prop().

getcheckbox.prop('checked', true); 

updated fiddle


the code can rewritten as

// cache checkbox object var checkbox = $("#paid-change");  // function toggle checkbox value , state function togglecheckbox() {     // change 'checked' property     checkbox.prop('checked', function(i, checked) {         return !checked;                           // invert checked status     }).val(function(i, val) {         return +this.checked;                      // change value     }); }  setinterval(togglecheckbox, 2000);                 // call function after each 2 seconds 

fiddle demo


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -