0

guys i have a function which when used it should check all the boxes and uncheck them. this was the original one that works great

     $('#checkAllId').change(function(){

    if($(this).attr('checked')){
     //uncheck all the checkboxes   
     $("input[type='checkbox']").each( 
       function() { 
          $(this).attr('checked',false);
       } 
     );
   }else{
      //check all the checkboxes  
      $("input[type='checkbox']").each( 
       function() { 
          $(this).attr('checked',true);
       } 
     ); 
   }
});  

however i adapted the function so i could target specific checkboxes with a certain class. here is the adapted version

    $('#checkAllId').change(function(){

    if($(this).attr('checked')){
     //uncheck all the checkboxes   
     $("input.mainobservations:checkbox").each( 
       function() { 
          $(this).attr('checked',false);
       } 
     );
   }else{
      //check all the checkboxes  
      $("input.mainobservations:checkbox").each( 
       function() { 
          $(this).attr('checked',true);
       } 
     ); 
   }
});  

This works to check all the boxes but it doesnt not work to uncheck all the boxes. Why is this?

user257033
  • 23
  • 1
  • 5

3 Answers3

0

You need to use .prop to set a checkbox to checked/unchecked instead of .attr:

$(this).prop('checked',true);
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
0

Use .prop(). Try this:

$(this).prop('checked',true);

Go through this for .prop() vs .attr()

Community
  • 1
  • 1
Kiran
  • 20,167
  • 11
  • 67
  • 99
0

Assuming you're using a version of jQuery that has access to prop() you should use that instead of attr(), and I'd suggest the following approach:

$('#checkAllId').change(function(){
    $('input.mainobservations[type="checkbox"]').prop('checked', this.checked);
});

Rudimentary JS Fiddle demo.

As to why, it's worth referring to the jQuery API for the prop() method:

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.

David Thomas
  • 249,100
  • 51
  • 377
  • 410