jeudi 20 octobre 2016

Jquery, Uncheck checkbox is two other checkboxes are unchecked

In my website, the user can create 'contact categories','item categories' and can decide which contact category is associated with which item categories. Multiple item categories can be associated with a contact category and vise versa.

http://ift.tt/2e4zXFe

Here is the HTML code.

<h1>
  New Contact
</h1>

<input type="checkbox" value="1" id="user_name">Contact category 1<br>
<input type="checkbox" value="2" id="user_name">Contact category 2<br>
<input type="checkbox" value="3" id="user_name">Contact category 3<br><br>

<input type="checkbox" value="a" id="user_name">Item category a<br>
<input type="checkbox" value="b" id="user_name">Item category b<br>
<input type="checkbox" value="c" id="user_name">Item category c

and the JQuery

var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");

var chka = $("input[type='checkbox'][value='a']");
var chkb = $("input[type='checkbox'][value='b']");
var chkc = $("input[type='checkbox'][value='c']");

chk1.on('change', function() {
  chka.prop('checked', this.checked);
  chkb.prop('checked', this.checked);
});

chk2.on('change', function() {
  chkb.prop('checked', this.checked);
});

chk3.on('change', function() {
  chka.prop('checked', this.checked);
  chkc.prop('checked', this.checked);
});

In this example contact category 1 is associated to item category a & b, contact category 2 is associated to item category b and contact category 3 with item category a & c.

SITUATION: A user adds a new contact. The user places the new contact to contact category 1 & 2. That way, Item category a & b get's activated through the JQuery code.

PROBLEM: If the user unchecks contact category 1, both item category a & b get's deactivated. While item category b should still be checked, because contact category 2 is still checked.

SIDENOTE: In practice, this won't be just 3 categories each. But a larger scale, so I hope this can be solved with something like.

chk1.on('checked', function() {
  chka++;
  chkb++;
if (chka > 0) chka.prop('change', this.checked);
});

chk1.on('unchecked', function() {
  chka--;
  chkb--;
if (chka > 0) chka.prop('change', this.checked);
});




Aucun commentaire:

Enregistrer un commentaire