Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 735
uxcode Avatar asked Jun 27 '14 04:06

uxcode


People also ask

What is the difference between prop and attribute in jQuery?

As of jQuery 1.6, the .prop () method provides a way to explicitly retrieve property values, while .attr () retrieves attributes. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop () method.

What is the use of props property in HTML?

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop () method should be used to set disabled and checked instead of the .attr () method.

Why is prop () not allowed in Internet Explorer?

In Internet Explorer prior to version 9, using .prop () to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp ()) before the DOM element is removed from the document.

What is the working statement $ (box) prop checked for?

The working statement $ ('#box').prop ('checked') you mentioned returns the checked property value instead of setting. Show activity on this post. Show activity on this post. $ ('#box').prop ('checked', false) is a setter version, it would return the element on which the .prop () method has been invoked, not a boolean result.


2 Answers

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.

like image 89
Adil Avatar answered Oct 04 '22 01:10

Adil


  if ($('#box').prop('checked')==false) {
      $('.form').append('<p>Checkbox is not checked.</p>');
  }
like image 20
Amarnath R Shenoy Avatar answered Oct 04 '22 00:10

Amarnath R Shenoy