Reputation: 67193
I'm trying to update a large web application that uses an extended version of Cory S.N. LaViska's jQuery.multiSelect plugin.
I updated to the latest code and it fixed a problem I was encountering. However, it introduced a new problem: Checking the Select All option now unchecks everything instead of checking it.
I'm not super advanced in JavaScript but have isolated the problem to the following code:
currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
if ($(this).attr('checked') == true)
$(this).parent().parent().find('INPUT:checkbox').attr('checked', true).parent().addClass('checked');
else
$(this).parent().parent().find('INPUT:checkbox').attr('checked', false).parent().removeClass('checked');
});
The problem is that $(this).attr('checked')
returns "checked". And so $(this).attr('checked') == true
will always be false. And the code never detects that this option is, in fact, checked!
Okay, so I understand the problem. But why would it ever be written this way, and what is the most reliable way to fix this? I'd be interested to know how a JavaScript/jQuery expert would address this.
Upvotes: 0
Views: 412
Reputation: 3735
checked
is a property, you should use prop
method, when a boolean attribute like disabled
or checked
is set to an element, the value is mapped to the relevant DOM property of the element(browser do this), as of jQuery 1.6
for modifying properties, prop
method should be used instead of attr
.
So you code should looks like this
currentMultiSelect.next('.multiSelectOptions').find('INPUT.selectAll').click(function () {
if ($(this).is(':checked'))
$(this).parent().parent().find('INPUT:checkbox').prop('checked', true).parent().addClass('checked');
else
$(this).parent().parent().find('INPUT:checkbox').prop('checked', false).parent().removeClass('checked');
});
Better if you use .is(":checked")
for checking whether the checkbox is checked or not. But use prop
to set the checked property of checkbox
.
Upvotes: 1
Reputation: 105
Rather than using $(this).attr('checked') == true
which will return a string try $(this).prop('checked') == true
$.prop()
will return boolean true
when the element is checked or boolean false
when it is not.
A little extra information on $.attr()
is it returns the contents of the attribute. So if your html is:
<input id="elem" type="checkbox" checked="checked" />
Then $('#elem').attr("checked")
is only going to return the string inside that attribute of the selected element.
If you really wanted to use $.attr()
you could do this.
if ($(elem).attr("checked") != '') { ... }
Upvotes: 1