Is there a bug with radio buttons in jQuery 1.9.1?
Asked Answered
E

2

11

I've been trying to programatically select radio buttons with jQuery, something I thought would be as simple as changing the checked attribute.

However, the following code doesn't seem to do what is expected in jQuery 1.9.1 in Chrome/Firefox.

Expected behaviour: Click the div enclosing the radio button -> 'checked' attribute gets set -> renders checked in the DOM.

Actual behaviour: Click the div enclosing the radio button -> 'checked' attribute gets set -> renders checked in the DOM for the first and second button clicked, subsequent buttons don't render as checked.

jQuery:

$('div.form-type-radio').on('click', function () {    
    var Id = $(this).find('input[type=radio]').attr('id');   
    $('form input[type=radio]:not(#'+Id+')').removeAttr('checked');   
    $('#' + Id).attr('checked', 'checked');    
    console.log($('#' + Id));    
});

Here's a jsFiddle - http://jsfiddle.net/GL9gC/

I've tried the same code with previous versions of jQuery and it all works as expected.

Emasculate answered 5/4, 2013 at 22:46 Comment(2)
Not that it has anything to do with this, but why the heck would you get the element, then the ID, and a few lines below use the ID to get the element, again? (not works with elements as well). Your entire function could be just $('input[type=radio]', this).prop('checked', true);Kassandra
That was just left over from some head scratching and debugging, just being absolutely sure I had the ID.Emasculate
A
24

In this case, you should use prop() instead of attr()/removeAttr().

Here's a working jsFiddle.

jQuery:

$('div.form-type-radio').on('click', function () {
    var Id = $(this).find('input[type=radio]').prop('id');
    $('form input[type=radio]:not(#'+Id+')').prop('checked');
    $('#' + Id).prop('checked', 'checked');
    console.log($('#' + Id));
});
Amaranth answered 5/4, 2013 at 22:49 Comment(2)
Thanks you, I guess I should have read this (jQuery docs):: "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. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property"Emasculate
I gone nuts since I couldn't understand why attr wasn't working for a project using 2.1.4. Good to know.Rawls
K
2

LIVE DEMO

$('div.form-type-radio').on('click', function () {    
    $(this).find(':radio').prop({checked: true});
});

http://api.jquery.com/prop/

Kiel answered 5/4, 2013 at 22:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.