painotpi
painotpi

Reputation: 6996

.attr() checkbox issue with jQuery v1.9.1

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

Answers (3)

Wikitude Developer
Wikitude Developer

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

Ram
Ram

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;
    });
});

http://jsfiddle.net/3rQvj/

Upvotes: 5

jah
jah

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

Related Questions