How to disable and uncheck checkboxes with checkboxes?

I have a jquery script that disables all checkboxes on a line and marks them as marked:

$(function() {
  enable_cb();
  $("#group1").click(enable_cb);
});

function enable_cb() {
  if (this.checked) {
     $("input.group1").attr("disabled", true);
     $("input.group1").attr("checked", true);
  } else {
     $("input.group1").removeAttr("disabled","checked");

  }
}

      

Here is my fiddle with html: http://jsfiddle.net/3fksv/16/

I want the rest of the checkboxes to appear active again and the checkboxes unchecked. What am I doing wrong in my script?

+3


source to share


3 answers


I don't think you can remove two attributes at once. You may have to use two function calls removeAttr()

-

$("input.group1").removeAttr("disabled");
$("input.group1").removeAttr("checked");

      



As @nickf correctly pointed out , these commands can also be encoded -

$("input.group1").removeAttr("disabled").removeAttr("checked");

      

+2


source


checked

and disabled

are properties, and for jQuery 1.6 you should use prop

method instead of attr

.

function enable_cb() {
   $("input.group1")
         .prop("disabled", this.checked)
         .prop("checked", this.checked);
}

      



http://jsfiddle.net/JeqE5/

+5


source


DEMO: http://jsfiddle.net/3fksv/18/

function enable_cb() {
   if (this.checked) {
      $("input.group1").attr("disabled", 'disabled');
      $("input.group1").attr("checked", 'checked');
   } else {
      $("input.group1").removeAttr("disabled","checked");
   }
}

$(function() {
   $("input.group1").attr("disabled", 'disabled');
   $("input.group1").attr("checked", 'checked');
   $("#group1").click(enable_cb);
});

      

0


source







All Articles