jQuery .prop('checked', false) does not work

uxcode picture uxcode · Jun 27, 2014 · Viewed 48.4k times · Source

HTML:

<form class="form">
    <input type="checkbox" id="box" /> Check Me!
</form>

JS:

$(window).load(function() {
    var myFunc = function() {
        if($('#box').prop('checked', false)) {
            $('.form').append('<p>Checkbox is not checked.</p>');
        }
    }

    $('#box').on('change', myFunc);
});

Here is a JSFiddle http://jsfiddle.net/3PYm7/

When I use $('#box').prop('checked', false) as a condition for the if statement it does not work, but ! $('#box').prop('checked') works just fine!

Answer

Adil picture Adil · Jun 27, 2014

The statement $('#box').prop('checked', false) does not return boolean rather set the checked property to false so should not be used in condition and it normal behaviour

if($('#box').prop('checked', false))

Could be changed to test using is() with :checked selector.

if($('#box').is(':checked'))

or

if($('#box:checked').length)

You can get the best performance by using the native javascript

if(document.getElementById('box').checked)

The working statement $('#box').prop('checked') you mentioned returns the checked property value instead of setting.