jQuery set radio button
Asked Answered
L

14

149

I am trying to set a radio button. I want set it by using the value or the id.

This is what I've tried.

$('input:radio[name=cols]'+" #"+newcol).attr('checked',true);

newcol is the id of the radio button.

Maybe a little edit is in order.

There are two sets of radio boxes one with cols and the other with rows. So I see the point in not using id's. My bad. So I have as an example:

<input type="radio" name="rows" class="listOfCols" 
   style="width: 50%; " value="Site"></input>

and

<input type="radio" name="cols" class="listOfCols" 
   style="width: 50%; "  value="Site"></input>

with the id's removed, and I need to set the correct one.

Libove answered 1/3, 2012 at 22:22 Comment(1)
possible duplicate of how to set radio option checked onload with jQueryUndeviating
B
215

Your selector looks for the descendant of a input:radio[name=cols] element that has the id of newcol (well the value of that variable).

Try this instead (since you're selecting by ID anyway):

$('#' + newcol).prop('checked',true);

Here is a demo: http://jsfiddle.net/jasper/n8CdM/1/

Also, as of jQuery 1.6 the perferred method of altering a property is .prop(): http://api.jquery.com/prop

Bitch answered 1/3, 2012 at 22:25 Comment(2)
+1 for prop vs attr. attr deprecated for properties and no longer work in jQuery 2.0 ))Ingressive
@FedericoJ's answer with using an array should be the accepted one.Heartburn
E
109

I found the answer here:
https://web.archive.org/web/20160421163524/http://vijayt.com/Post/Set-RadioButton-value-using-jQuery

Basically, if you want to check one radio button, you MUST pass the value as an array:

$('input:radio[name=cols]').val(['Site']);
$('input:radio[name=rows]').val(['Site']);
Ellaelladine answered 1/8, 2013 at 12:33 Comment(4)
Hello That Link has no Suggested content in it. Why are you guys keep rejecting my edit to remove the link. It does not contains anything regards the matter.Jeweljeweler
@MenukaIshan, the point is: Give credit. The link is available in web.archive.org, and the guy who wrote it the first time and from who I get the idea of the answer has to receive its credit. Don't remove the link, and if you want to see the original post, copy and paste the link (I don't know why it's going to the old page instead of the web.archive.org)Ellaelladine
@Chococroc You haven't configured the Markdown of question correctly. I saw the Web archive version and linked it correctly. After Review It'll correctly link to the site.Jeweljeweler
It seems like this should be the accepted answer since it is the solution mentioned in the jQuery docsKarimakarin
M
18

In your selector you seem to be attempting to fetch some nested element of your radio button with a given id. If you want to check a radio button, you should select this radio button in the selector and not something else:

$('input:radio[name="cols"]').attr('checked', 'checked');

This assumes that you have the following radio button in your markup:

<input type="radio" name="cols" value="1" />

If your radio button had an id:

<input type="radio" name="cols" value="1" id="myradio" />

you could directly use an id selector:

$('#myradio').attr('checked', 'checked');
Martens answered 1/3, 2012 at 22:24 Comment(2)
If there are multiple radios with the cols name then $('input:radio[name="cols"]').attr('checked', 'checked'); will select just the last one. It will run the code on each, but every-time you set the checked property, the previously set element gets unset. Here's a demo: jsfiddle.net/jasper/n8CdM/2Bitch
@Jasper, yes, that's true. It is why I suggested using an id selector.Martens
K
15

You can try the following code:

$("input[name=cols][value=" + value + "]").attr('checked', 'checked');

This will set the attribute checked for the radio columns and value as specified.

Knorr answered 16/9, 2013 at 12:5 Comment(1)
...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. Source: api.jquery.com/attrBitch
W
10

Why do you need 'input:radio[name=cols]'. Don't know your html, but assuming that ids are unique, you can simply do this.

$('#'+newcol).prop('checked', true);
Whiskey answered 1/3, 2012 at 22:25 Comment(0)
O
6

Try this:

$("#" + newcol).attr("checked", "checked");

I've had issues with attr("checked", true), so I tend to use the above instead.

Also, if you have the ID then you don't need that other stuff for selection. An ID is unique.

Ostium answered 1/3, 2012 at 22:27 Comment(4)
prop is better than attr for things like thisAlic
attr is gone in jQuery 1.9+ Use prop.Pastrami
You're right, but ultimately it depends on your specific situation. If your code will be always running with jQuery 1.6+, then prop is the way to go. But if your code may be running on older versions then the solution isn't as straightforward. For example, I maintain the jQuery PickList plugin, and we support jQuery 1.4+, so simply using prop is not an option. This is an open ticket, so if you have any elegant suggestions I would love to hear them; I just haven't had time to do the research yet.Ostium
The problem is that even if your solution might be more backward-compatible it simply doesnt work in this case: Select A, it will get new checked="checked" attribute and browser will show it as checked, then select B and the same will happen. Now when you select A again it will already have checked="checked" attribute and nothing will change. As a side effect of that B will still be selected, not A.Shuttlecock
P
4

Using .filter() also works, and is flexible for id, value, name:

$('input[name="cols"]').filter("[value='Site']").attr('checked', true);

(seen on this blog)

Pelasgian answered 17/8, 2017 at 0:17 Comment(1)
I believe this is an equally valid answer, but it should use the prop() method: $('input[name="cols"]').filter("[value='Site']").prop('checked', true);. The user wants to set by "value or id". There may be times were you do not want to set id values for every radio option, so getting by name and filtering by value is useful.Damico
S
3

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);
Stethoscope answered 9/8, 2020 at 19:44 Comment(0)
A
2

Since newcol is the ID of the radio button, You can simply use it as below.

$("#"+newcol).attr('checked',true);
Avicenna answered 1/3, 2012 at 22:25 Comment(0)
A
2

Combining previous answers:

$('input[name="cols"]').filter("[value='Site']").click();
Abutter answered 13/9, 2018 at 11:59 Comment(0)
W
1

in my case, i use (to active Css animation when click radio)

$('input:radio[name="cols"]').trigger ('click');
Wordbook answered 11/5, 2021 at 4:41 Comment(0)
T
0

You can simply use:

$("input[name='cols']").click();
Tamandua answered 23/4, 2015 at 9:27 Comment(0)
G
0

The chosen answer works in this case.

But the question was about finding the element based on radiogroup and dynamic id, and the answer can also leave the displayed radio button unaffected.

This line does selects exactly what was asked for while showing the change on screen as well.

$('input:radio[name=cols][id='+ newcol +']').click();
Gratuitous answered 20/10, 2016 at 15:2 Comment(0)
D
0

$('#a_state option[value="'+a_state+'"]').prop("selected", true);

prop() is the best option because attr sometimes works randomly.

Dessiatine answered 28/4, 2021 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.