I can't figure this one out. According to W3 Schools, the checked property sets or returns the checked state of a checkbox.
So why does $('input').checked ? $('div').slideDown() : $('div').slideUp();
not work?
Using prop however, does work.
$('input').prop('checked') ? $('div').slideDown() : $('div').slideUp();
This is for a checkbox that is checked based on a database value.
The checked is a boolean attribute meaning that the corresponding property is true if the attribute is present, even if the attribute has no value or is set to empty string value or "false". The checked attribute value doesn't change with the state of the checkbox, whereas the checked property changes.
.attr('checked') //returns checked .prop('checked') //returns true .is(':checked') //returns true prop method returns Boolean value for checked, selected, disabled, readOnly..etc while attr returns defined string.
The prop () method provides a way to get property values for jQuery 1.6 versions, while the attr () method retrieves the values of attributes. The checked is a boolean attribute meaning that the corresponding property is true if the attribute is present, even if the attribute has no value or is set to empty string value or "false".
Now see that the attribute value is still jQuery while the value property has been changed to Welcome jQuery. The property always represents the current state while the attribute (except in old versions of IE) represents the initial state or is meant for HTML attributes since they are strictly defined.
checked
is a DOM element property so use it on DOM elements instead of jQuery objects.
$('input')[0].checked
if you have a jQuery object, use prop
instead of attr
since you are checking a property. Just as a reference:
$("<input type='checkbox' checked='checked'>").attr("checked") // "checked"
$("<input type='checkbox' checked='foo'>").attr("checked") // "checked"
$("<input type='checkbox' checked>").attr("checked") // "checked"
$("<input type='checkbox'>").attr("checked") // undefined
Whereas [0].getAttribute("checked")
will return the actual value.
prop
will return true
or false
based on whether or not the attribute exists at all
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