Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't .attr("checked", true) work in Jquery 1.7 and up

Tags:

jquery

this code works in jQuery, ver. 1.6

<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />
<input type="checkbox" class="radio" value="1" name="sameName" />

$("input:checkbox").click(function() {
    if ($(this).attr("checked") === true) {
        var group = "input:checkbox[name='" + $(this).attr("name") + "']";
        $(group).attr("checked", false);
        $(this).attr("checked", true);
    } else {
        $(this).attr("checked", false);
    }
});​

BUT if I change the code using new methods of jQuery 1.7 it wont work? why? thanks for yr time :

$("input:checkbox").on('click', function() {
    if ($(this).attr("checked") === true) {
        var group = "input:checkbox[name='" + $(this).attr("name") + "']";
        $(group).attr("checked", false);
        $(this).attr("checked", true);
    } else {
        $(this).attr("checked", false);
    }
});​
like image 250
YoniGeek Avatar asked Dec 09 '25 13:12

YoniGeek


2 Answers

Use .prop('checked',true) instead of .attr.

http://api.jquery.com/prop

Also, if ($(this).attr("checked") === true) can be shortened to simply

if ($(this).prop("checked")) {
like image 132
Blazemonger Avatar answered Dec 12 '25 08:12

Blazemonger


attr returns a string. You should be using .prop to set the checked property for jQuery 1.6+

$("input:checkbox").on('click', function() {
    if (this.checked) {
        var group = "input:checkbox[name='" + $(this).attr("name") + "']";
        $(group).prop("checked", false);
        $(this).prop("checked", true);
    } else {
        $(this).prop("checked", false);
    }
});​

From jQuery .prop() docs

The .prop() method should be used to set disabled and checked instead of the .attr() method.

like image 25
wirey00 Avatar answered Dec 12 '25 07:12

wirey00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!