3

I have 'chain' of checkboxes (parent checkbox and childs), and problem is:

When first clicking on 'parent' checkbox it is working well, but after that when clicking on 'childs', the 'parent' checkbox then isn't doing what is supposed. Parent is checking/unchecking childs except the child which was pressed before.

Here is code:

JavaScript

checks_bind();
function checks_bind(){
  $("#x_main").off('click');
  $("#x_main").on('click',function(){
  var obj   = $(this);
    var val = obj.is(':checked');
    $("#checks").find("input[type='checkbox']").attr('checked',val);
  });
}

HTML

<input id='x_main' type='checkbox'/>Main<br>
<p>--------------------------------</p>
<div id='checks'>
<input type='checkbox'/>1<br>
<input type='checkbox'/>2<br>
</div>
<p>--------------------------------</p>
<i>1 - Click on 1 or 2 <br>2 - Try <b>Main</b> checkbox. <br>
3 - Main checkbox isn't working</i>

jsfiddle example

And one more question:

Is it good to use .on('click.namespace') on checkboxes since it's working well? I can use .change() method, but I want to call .off('click.namespace') (or something to unbind) before .on() each time when calling the function.

Max Maximilian
  • 591
  • 2
  • 20

2 Answers2

4

As checked is a property, You need to use .prop() instead of .attr()

$("#checks").find("input[type='checkbox']").prop('checked', val);

Updated Fiddle, A good read .prop() vs .attr()

If you want to use .off() then its advisable to use namespaced event.

Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Try this: user 'prop' instead of attribute and you can check all or uncheck all as per checked condition of main check box. Also, you can check the count of all checkbox to check /uncheck main checkbox. see below

Note: bind click handler when DOM is ready hence user $(document).ready or $(function(){})

$(function(){
    $("#x_main").on("change", function(){
    $("#checks").find("input[type='checkbox']").prop("checked",$(this).is(":checked"));
  });

  $("#checks input[type='checkbox']").on("change", function(){
      var total = $("#checks").find("input[type='checkbox']").length;
      var checked = $("#checks").find("input[type='checkbox']:checked").length;
      $("#x_main").prop("checked",total==checked);
  });
});

JSFiddle Demo

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57