Set radio button 'checked' in jquery based on ID
Asked Answered
M

3

12

I have two radio buttons with the same name, one is checked by default. How can you check or uncheck a radio button in jQuery when selecting from id?

I've tried:

$('#radio1').attr('checked','checked');
$('#radio1').attr('checked', true);

Nothing seems to work.. any ideas?

Thank you!

Monanthous answered 25/6, 2010 at 22:11 Comment(1)
Also, use $( selector ).prop("checked", true) for >= Jquery 1.6Trod
D
21

You can not have same id (#radio1) more than once, use a class instead.

$('.radio1').attr('checked', true);
$('.radio2').attr('checked', true);

The id should be used once per element per page.

If you want to check/uncheck on click however, you may do like:

$('#someid').click(function(){
  $('#radio1').attr('checked', true);
});

Or

$('#someid').click(function(){
  $('#radio1').attr('checked', this.checked);
});
Denadenae answered 25/6, 2010 at 22:14 Comment(2)
Dave is saying same name, not same idLamblike
@Filippo, Dave does not know what is id, name and does not see the difference between them.Henryk
L
9

If you have the radios like:

<input type="radio" id="radio1" name="same-radio-name" />
<input type="radio" id="radio2" name="same-radio-name" />

So, to check the second and uncheck the first one:

$('#radio2').attr('checked', true);

Viceversa:

$('#radio1').attr('checked', true);

Just another thought, are you using the radio as a JQuery UI button? If so you may also need to refresh it like:

$('#radio1').attr('checked', true).button("refresh");
Lamblike answered 21/12, 2010 at 21:30 Comment(0)
I
-1

Well, if you wanna get a value from the input radio to upload this value from your database you can try with this simple code:

 var selValue = $('input[name=rbnNumber]:checked').val();

Where you put the name of the variable "selValue" and inside of this you specific the name of the radio group "rbnNumber". All this inside the function that you work and done.

Inofficious answered 25/4, 2013 at 19:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.