Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a bug with radio buttons in jQuery 1.9.1?

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.

like image 940
Simon Avatar asked Apr 05 '13 22:04

Simon


People also ask

Is radio checked in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.

How do I check if a Radiobutton is enabled in Javascript?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

Is radio checked Javascript?

Select all radio buttons by using a DOM method such as querySelectorAll() method. Get the checked property of the radio button. If the checked property is true , the radio button is checked; otherwise, it is unchecked.


2 Answers

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));
});
like image 103
dsgriffin Avatar answered Oct 21 '22 01:10

dsgriffin


LIVE DEMO

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

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

like image 24
Roko C. Buljan Avatar answered Oct 21 '22 03:10

Roko C. Buljan