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!
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.
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.
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.
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.
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.
if ($('#box').prop('checked')==false) {
$('.form').append('<p>Checkbox is not checked.</p>');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With