jeudi 27 avril 2017

JQuery: Checkbox Chain not working properly

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.




Aucun commentaire:

Enregistrer un commentaire