8

I need help with auto checking checkboxes in treeview.

I have a treeview, when I click checkbox, all child items in list will have their checkboxes automatically checked. The problem is it won't work.

treeview.find('input[type=checkbox]').each(function () {
    $j(this).click(function () {
        if ($j(this).is(':checked')) {
            $j(this).siblings('ul').find('input[type=checkbox]').attr('checked', 'checked');
        } else {
            $j(this).siblings('ul').find('input[type=checkbox]').removeAttr('checked');
        }
    });
});

So the code says it all, I find all checkboxes, and on each I bind click event. When the item is clicked, it checks if it is checked, then find all checkboxes and set their attribute to checked, else find all checkboxes and remove their checked attribute. My selectors work okay, so that isn't the problem.

When I click on a checkboxes, all checkboxes get checked, and when I uncheck, it's still working. But on another try, it doesn't work anymore! That's very weird! And the weirdest thing is that when I inspect code, I can see on checkbox that it has checked="checked" but browser won't render the checked state (actually this is the main problem).

1
  • 6
    Try .prop() instead of .attr(). Commented Jun 24, 2013 at 15:54

1 Answer 1

16

Use:

$el.prop('checked', true) // to check the box
$el.prop('checked', false) // to uncheck the box

Instead of:

$el.attr('checked', 'checked') // to check the box
$el.removeAttr('checked') // to uncheck the box

This is because you need to change the checked state of the box, not the checked attribute. The checked attribute is just for the initial state of the checkbox.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.