In jQuery, how do I select an element by its name attribute?
Asked Answered
M

18

333

I have 3 radio buttons in my web page, like below:

<label for="theme-grey">
  <input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-pink">
  <input type="radio" id="theme-pink" name="theme" value="pink" />Pink</label>
<label for="theme-green">
  <input type="radio" id="theme-green" name="theme" value="green" />Green</label>

In jQuery, I want to get the value of the selected radio button when any of these three are clicked. In jQuery we have id (#) and class (.) selectors, but what if I want to find a radio button by its name, as below?

$("<radiobutton name attribute>").click(function(){});

Please tell me how to solve this problem.

Marc answered 12/6, 2009 at 11:10 Comment(5)
you don't strictly need to specify the attribute 'for', as long as the fields are included between their corresponding 'label' tagsKilgore
jQuery 1.8 and above changes this.... I added an answer below explaining.Dionne
A1rPun's answer is the best: a non-jQuery one-liner!Harriette
Used a radio button for maintaining state in my js app. Debugged for a good one hour before checking this thread. Check this outFey
In plain JS: document.querySelectorAll("input:radio[name=theme]").forEach(function() { this.onclick=function() { var value = this.value; }; });Shane
P
346

This should do it, all of this is in the documentation, which has a very similar example to this:

$("input[type='radio'][name='theme']").click(function() {
    var value = $(this).val();
});

I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.

Phosphor answered 12/6, 2009 at 11:15 Comment(7)
@gargantaun - if you click a radio button, what happens to it?Phosphor
Good point. Although it's still not "How to get selected radiobutton value using its name in jQuery?". It's "How to get selected radiobutton value when clicking on it using jQuery?". A small difference, but one that baffled me for a bit.Wilfredwilfreda
According to the question this answer is correct. in global view we go for clayton's answer.Overplus
This was not the answer I was looking for because it still took the value of the first radio button in the list. The answer below is the correct answer.Dorice
@AdamLevitt: You don't understand the question and/or the answer if you think this answer is wrong.Phosphor
As of jQuery 1.8 use [type='radio'] instead of :radio that way jQuery can take advantage of the performance boost provided by the native DOM querySelectorAll() method.Regrate
@PaoloBergantino answer is 100% correct because it returns the value after clicking the desired radio button.@Clayton Rabenda answer does not give this.Exalted
M
187

To determine which radio button is checked, try this:

$('input:radio[name=theme]').click(function() {
  var val = $('input:radio[name=theme]:checked').val();
});

The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.

Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.

Micahmicawber answered 12/6, 2009 at 15:6 Comment(4)
Base don how I READ the question, this was the answer I needed. :checked is what i was missing in my equation. Thanks.Neopythagoreanism
As of jQuery 1.8 use [type='radio'] instead of :radio that way jQuery can take advantage of the performance boost provided by the native DOM querySelectorAll() method.Regrate
I gave a space after colon and before "checked" by mistake. So please make sure there is no space.Barrator
A useful answer for those not wanting to get the value from a click event handler. Otherwise, you must use :checked to find which button is checked, for example, with a form submit event handler where the this keyword does not map to the clicked button.Piggish
H
156
$('input:radio[name=theme]:checked').val();
Heaves answered 4/6, 2013 at 5:42 Comment(2)
I went on simply with $("input[name=theme]:checked").val(); (leaving the :radio part out and it seems to work fine in IE, FF, Safari and Chrome. I had to work with jQ v 1.3... Of course, that means there is only one element named 'theme'Bidet
This is the best answer IMO, it says "get me the value of the CHECKED radio with THIS name". No need for events, etc.Bandy
T
39

another way

$('input:radio[name=theme]').filter(":checked").val()
Toneme answered 30/11, 2013 at 5:34 Comment(2)
This one is useful if you are interested in grabbing the value +1Teamster
This is solid because you can use a variable to keep the radio buttons, e.g. $themeRadios = $('input:radio[name=theme']) to set any event handlers and then get the value by using the filter, e.g. $themeRadios.filter(":checked").val().Mathilda
E
20

This works great for me. For example you have two radio buttons with the same "name", and you just wanted to get the value of the checked one. You may try this one.

$valueOfTheCheckedRadio = $('[name=radioName]:checked').val();
Eunaeunice answered 7/9, 2012 at 17:38 Comment(1)
The reason this answer is better than the currently-accepted 230+ upvoted answer is because this answer also accounts for when the user interacts with a radio button by keyboard.Jaffna
B
16

The following code is used to get the selected radio button value by name

jQuery("input:radio[name=theme]:checked").val();

Thanks Adnan

Boschvark answered 6/3, 2013 at 10:45 Comment(1)
hmm .. didn't I fix your code formatting in your last reply? Please take care of it yourself :-)Cavorelievo
M
14

For anyone who doesn't want to include a library to do something really simple:

document.querySelector('[name="theme"]:checked').value;

jsfiddle

For a performance overview of the current answers check here

Mcanally answered 30/9, 2014 at 12:34 Comment(1)
Thanks for this answer. Because I was unable to get the accepted answer to work in any form.Preeminence
D
13

I found this question as I was researching an error after I upgraded from 1.7.2 of jQuery to 1.8.2. I'm adding my answer because there has been a change in jQuery 1.8 and higher that changes how this question is answered now.

With jQuery 1.8 they have deprecated the pseudo-selectors like :radio, :checkbox, :text.

To do the above now just replace the :radio with [type=radio].

So your answer now becomes for all versions of jQuery 1.8 and above:

$("input[type=radio][name=theme]").click(function() { 
    var value = $(this).val(); 
}); 

You can read about the change on the 1.8 readme and the ticket specific for this change as well as a understand why on the :radio selector page under the Additional Information section.

Dionne answered 3/10, 2012 at 17:2 Comment(1)
:checked is not deprecated. So you can use $("input[type='radio'][name='theme']:checked")Regrate
C
9

If you'd like to know the value of the default selected radio button before a click event, try this:

alert($("input:radio:checked").val());
Crimson answered 24/6, 2011 at 18:38 Comment(0)
M
6

You can use filter function if you have more than one radio group on the page, as below

$('input[type=radio]').change(function(){
    var value = $(this).filter(':checked' ).val();
    alert(value);
});

Here is fiddle url

http://jsfiddle.net/h6ye7/67/

Masefield answered 10/3, 2015 at 23:17 Comment(0)
V
4
<input type="radio" name="ans3" value="help"> 
<input type="radio" name="ans3" value="help1">
<input type="radio" name="ans3" value="help2">

<input type="radio" name="ans2" value="test"> 
<input type="radio" name="ans2" value="test1">
<input type="radio" name="ans2" value="test2">

<script type="text/javascript">
  var ans3 = jq("input[name='ans3']:checked").val()
  var ans2 = jq("input[name='ans2']:checked").val()
</script>
Vigilant answered 4/7, 2012 at 6:33 Comment(0)
C
4

If you want a true/false value, use this:

  $("input:radio[name=theme]").is(":checked")
Chavira answered 5/8, 2013 at 16:17 Comment(0)
T
3

Something like this maybe?

$("input:radio[name=theme]").click(function() { 
 ...
}); 

When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.

Tripartite answered 12/6, 2009 at 11:13 Comment(1)
The @ is invalid as of jQuery 1.3 (deprecated prior to that, even). blog.jquery.com/2009/01/05/help-test-jquery-13-beta-2 "Old, XPath, style attribute selectors: [@attr=value]. These have been deprecated for quite some time - and we’re finally removing them. To fix it just remove the @!"Rachal
U
3

I you have more than one group of radio buttons on the same page you can also try this to get the value of radio button:

$("input:radio[type=radio]").click(function() {
    var value = $(this).val();
    alert(value);
});

Cheers!

Undercurrent answered 14/1, 2015 at 18:1 Comment(0)
I
2

can also use a CSS class to define the range of radio buttons and then use the following to determine the value

$('.radio_check:checked').val()
Indemnification answered 14/6, 2012 at 16:37 Comment(0)
S
1

This worked for me..

HTML:

<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>

Jquery:


    $(".radioClass").each(function() {
        if($(this).is(':checked'))
        alert($(this).val());
    });

Hope it helps..

Syndrome answered 26/2, 2013 at 8:11 Comment(0)
C
0
$('input:radio[name=theme]').bind(
  'click',
  function(){
    $(this).val();
});
Cash answered 12/6, 2009 at 18:58 Comment(0)
E
0

You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.

You create RadioButton control in ASP.NET as below:

<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />

And ASP.NET renders following HTML for your RadioButton

<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>

For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.

The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following

$('span.radios input:radio').click(function() {
    var value = $(this).val();
});
Electrocardiogram answered 19/6, 2015 at 3:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.