mercredi 12 août 2015

How to use jQuery for listening if checkbox is changed not by clicking?

I have a number of checkboxes that change state(checked ,not checked) using another jQuery statement:

Elements:

<input type="checkbox" id="select_a">select group A</input>
<input type="checkbox" id="select_b">select group B</input>
<input type="checkbox" id="mix">select mix</input>

<div id="group_a">
    <input type="checkbox" id="a_1">group A_1</input>
    <input type="checkbox" id="a_2">group A_2</input>
</div>
<div id="group_b">
    <input type="checkbox" id="b_1">group B_1</input>
    <input type="checkbox" id="b_2">group B_2</input>
</div>

JQUERY

jQuery("#select_a").click(function () {
    if (this.checked) jQuery("div#group_a input:checkbox").prop("checked", true);
    else jQuery("div#group_a input:checkbox").prop("checked", false);
});
jQuery("#select_b").click(function () {
    if (this.checked) jQuery("div#group_b input:checkbox").prop("checked", true);
    else jQuery("div#group_b input:checkbox").prop("checked", false);
});
jQuery("#mix").click(function () {
    if (this.checked) {
        jQuery("#a_1").prop("checked", true);
        jQuery("#b_1").prop("checked", true);
    } else {
        jQuery("#a_1").prop("checked", false);
        jQuery("#b_1").prop("checked", false);
    }
});

I need a way to set a listener to each checkbox in the groups, I used this way which works like this:

jQuery("div input:checkbox").click(function(e){
    alert(e.target.id);
}); 

but this only works if the checkbox was clicked by the mouse, I would like a way to fire an event(set a listener) for each checkbox if it was checked by something other than the mouse.

Demo




Aucun commentaire:

Enregistrer un commentaire