0

I use $('#checkbox_all').attr('checked', false); to uncheck $('#checkbox_all') when i click for one of the others checkboxes. It works fine but when I click $('#checkbox_all') it is not going to be checked.

So $('#checkbox_all') is somehow doesn't work properly it is always unchecked.

What do I am missing? How to fix it?

Thank you!

$(document).ready(function () {

        $('#checkbox_all').attr('checked', true);

        $('input[id^="checkbox_"]').click(function () {
            $('#checkbox_all').attr('checked', false);
        });

        $('#checkbox_all').click(function () {
            alert("!!!");
        });
    });

3 Answers 3

2

You are setting checkbox_all to false when any checkbox is clicked even if it is checkbox_all. Also if you are using jQuery 1.7, you should be using prop() instead of attr(). Try this:

$(document).ready(function () {
    $('#checkbox_all').prop('checked', true);

    $('input[id^="checkbox_"][id!=checkbox_all]').click(function () {
        $('#checkbox_all').prop('checked', false);
    });

    $('#checkbox_all').click(function () {
        alert("!!!");
    });
});
2
  • The not statement can be consolidated into the selector, like this: input[id^="checkbox_"][id!=checkbox_all]
    – Austin
    Jul 27, 2012 at 14:23
  • 1
    @Austin Another reason why I love stackoverflow, I learn stuff even when I am helping others out.
    – Josh Mein
    Jul 27, 2012 at 14:27
2

#checkbox_all is included in the $('input[id^="checkbox_"]') selector, so it's being told to uncheck onclick.

2

Use prop instead of attr:

$('#checkbox_all').prop('checked', true);

prop deals with properties of the DOM, while attributes deals with attributes and their values. To use attr, which would change the attributes instead of the DOM's checked variable, you would do this:

$('#checkbox_all').attr('checked', "checked");

You can then find all checked checkboxes using jQuery's .is( condition ), like so:

$('#someCheckBox').is(":checked"); // returns true false

OR:

$('#someCheckBox').prop("checked"); // returns true false

Additionally, on click, you are changing the properties of #checkbox_all, wouldn't you want to change the properties of all other checkboxes? Like so:

$("input[type=checkbox]")
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.