Search code examples
jquerydom-traversal

Why does attr() not update the HTML when called a second time?


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);          
        });
    });

Solution

  • 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