Reputation: 6996
HTML:
<input type="checkbox" />
<span id="test">Click here</span>
JS:
$("#test").click(function () {
if ($(":checkbox").attr("checked") == undefined) {
$(":checkbox").attr("checked", "checked")
} else {
$(":checkbox").removeAttr("checked")
}
});
Fiddle: Link - v1.8.3
This works just fine, but, if I change the jquery version to 1.9.1, the checkbox doesn't get checked anymore. What is the issue?
Fiddle: Link - v.1.9.1
Although the inspect element
shows the checkbox is toggling the attribute, if I do a $(":checkbox").is(":checked")
in the console, I get false
as the output
Upvotes: 2
Views: 861
Reputation: 11
I also faced the same issue and you should refer below link to get proper idea http://jquery.com/upgrade-guide/1.9/#attr-versus-prop- Hope it solves your issue :)
Upvotes: 1
Reputation: 144689
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) and attr
and removeAttr
methods do not change the properties of an element, as of jQuery 1.6 for modifying properties, prop
method should be used instead of attr
.
$("#test").click(function () {
$('input[type=checkbox]').prop('checked', function(i, state){
return !state;
});
});
Upvotes: 5
Reputation: 1305
Why not just use a label? That way it would work without javascript.
<input type="checkbox" id="test" /><label for="test">Click me</label>
Upvotes: 0