charlie
charlie

Reputation: 481

jquery check all with each checkbox 'change' function

i have this jquery on my page which selects all checkboxes with a class of CheckInvoice

$("#checkAllInvoices").click(function(){
    $('.checkInvoice').not(this).prop('checked', this.checked);
});

i then have this which sees the change on the checkbox

$('#check').on('change', function() {

}

$('#check1').on('change', function() {

}

$('#check2').on('change', function() {

}

the 'on change' jquery works fine when i select each checkbox however when i use the check all, its not recognising it as a 'change'

Upvotes: 0

Views: 3040

Answers (1)

Tibrogargan
Tibrogargan

Reputation: 4603

There are a few things going on.

Firstly, can't see your HTML, but it seems like maybe you're using check as an id for every check box. This won't work, an id must be unique. I've replaced this with just using your check box class.

Secondly, you're trying to set the state of each checkbox based on the checkAllInvoices checkbox - but you're not iterating through each of them - you're just changing the state of the checkAllInvoices element. I've also removed the checkInvoice class from the checkAllInvoices element so you don't need to do the not(this) test

Thirdly (and the real answer), you need to trigger the change function to occur - not just change the state of the property

"use strict";

function init() {
    $("#checkAllInvoices").click(function(){
        var checked = this.checked;
        $('.checkInvoice').each(
            function() {
                if (this.checked != checked) $(this).trigger('click');
            }
        );
    });

    $('.checkInvoice').on('change', function() {
        console.log(this.value)
    });
}

$( document ).ready(init)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<form name="test">
<input type="checkbox" class="checkInvoice" value="1">1
<input type="checkbox" class="checkInvoice" value="2">2
<input type="checkbox" class="checkInvoice" value="3">3
<input type="checkbox" class="checkInvoice" value="4">4
<input type="checkbox" class="checkInvoice" value="5">5<br />
<input type="checkbox" id="checkAllInvoices">check all<br />
<br />
</form>
</body>

Upvotes: 3

Related Questions