Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS .checked vs jquery attr('checked'), what is the difference?

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.

like image 685
Jacob Raccuia Avatar asked Feb 26 '13 04:02

Jacob Raccuia


People also ask

What is the difference between the checked and checked attribute?

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.

What is the difference between is () and ATTR () methods in JavaScript?

.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.

What is the difference between prop () and ATTR () methods in jQuery?

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".

What is the difference between attribute and value in jQuery?

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.


1 Answers

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

like image 98
Dennis Avatar answered Oct 13 '22 12:10

Dennis