0

I have used the code:

<script type="text/javascript">
  $(window).load(function () {
    $(document).delegate(".checkall", "click", function(event) {
      $(this).closest("table").find(':checkbox').attr('checked', this.checked);
    });
  });
</script>

This code is working fine when I select/deselect the checkbox in header for the first time. But when I again select the checkbox then this code is not working. The checkboxes are not selected.

voloshin
  • 536
  • 7
  • 17
Neha
  • 3
  • 3
  • check this answer it will have everything you need:https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery Also you will need to wrap it in if statement: if($(this).closest("table").find(':checkbox').attr('checked')){ /*check code*/ }else {/*uncheck code*/} And use .prop better – pegla Sep 12 '17 at 07:48

1 Answers1

0

You should use .prop() instead of .attr(). And you have to check if an element is already checked.

...
  var $checkbox = $(this).closest("table").find(':checkbox');
  if ($checkbox.is(':checked')) $checkbox.prop('checked', false);
  else                          $checkbox.prop('checked', true);
...
voloshin
  • 536
  • 7
  • 17
  • I just replaced .attr with .prop in my mentioned above code. It is working fine. But when I deselects one of the check boxes in the column below, then the header checkbox should also be deselected automatically. But it is not happening. – Neha Sep 12 '17 at 09:40
  • I'm afraid I can't help you with that problem until I see your `html`. Create a jsfiddle so I can take a look. – voloshin Sep 12 '17 at 10:44
  • Iam unable to create jsfiddle .please suggest – Neha Sep 13 '17 at 06:06
  • I need to see your `html` to suggest anything. At this moment of time I can't suggest anything and can't see any reasons for desired behaviour of your script. Show me more code. – voloshin Sep 13 '17 at 07:59