Question

I have a script that is supposed to select all descendant input checkbox, when the ancestor checkbox is selected.

See here: http://jsfiddle.net/zJPfR/

When the top-level checkbox is selected, all checkboxes underneath are selected. If you unselect the checkbox, the checks are removed. However if you attempt to do this a second time, it doesn't work.

If I'm going about this incorrectly, please let me know.

Darius

        $('.poSelect').click(function() {
        var expandBox   = $(this).parents('.pohelpTbl').next('.expandBox');
        var receipts    = expandBox.find('input[type="checkbox"]');

        if ($(this).is(':checked')) {
            var status = true;
        } else {
            var status = false;
        }

        $(receipts).each(function (i) {
            var cb = $(this);
            cb.attr("checked",status);          
        });
    });
Was it helpful?

Solution 2

It should be

$('.poSelect').click(function() {
    var receipts    = $(this).closest('.pohelpTbl').next('.expandBox').find(':checkbox');

    receipts.prop('checked', this.checked);
});

There is no need to iterate through each of the receipts items, you can call .prop() directly on receipts.

Demo: Fiddle

OTHER TIPS

jQuery's .attr only uses the initial attributes. Use .prop instead of .attr to change the current DOM.
cb.attr("checked",status); => cb.prop("checked",status);

The checked attribute's presence is what shows the checkbox to be checked, not if the value of the attribute is being set to true or false.

change from this:

var cb = $(this);
cb.attr("checked",status);

to this:

var cb = $(this);
if (status){
    cb.attr("checked","checked");
}
else{
    cb.removeAttr("checked");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top