Leander
Leander

Reputation: 352

jQuery .prop('checked') not changing actual checked attribute in HTML

OK, this most probably is a rather dumb question but I am having difficulty wrapping my head around this...

On page load / generation I am adding checked="checked" to my <input type="checkbox" value="1"> via PHP based on the actual database entry.

Upon acting with the form I am reading the input's checked status via Javascript / jQuery in order to (AJAX-)submit the form and update the database entry.

The issue is that even when my JS-evaluation _this.is(':checked') returns false the actual HTML / DOM representation still show the checked attribute <input type="checkbox" value="1" checked="checked">.

I know that I could .removeAttr('checked') but that doesn't make sense (everything works) and is also not recommended (see this SO question...)


My question(s) would be: Is this normal behaviour? Should I simply disregard the inconsistence? What am I not getting here?

Thanks for your time + effort!

Upvotes: 2

Views: 2648

Answers (2)

luciandex
luciandex

Reputation: 645

More info:

jQuery/prop

Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337691

This is completely normal. The attribute you see in the source is the original state of the element. The underlying property - which is what prop() gets/sets - can be different.

Here's an example:

var $cb = $(':checkbox');

console.log('attr: ' + $cb.attr('checked'), 'prop: ' + $cb.prop('checked'));

$cb.prop('checked', false);

console.log('attr: ' + $cb.attr('checked'), 'prop: ' + $cb.prop('checked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" checked="checked" />

Note that even after setting prop('checked', false) the attr() still reads the checked attribute which was present when the page loaded.

It's for this reason you should always use prop() where possible.

Upvotes: 3

Related Questions