How do you get the checked value of asp:RadioButton with jQuery?
Asked Answered
M

4

8

I need to do something like this:

<asp:RadioButton ID="rbDate" runat="server" Text="Date" GroupName="grpPrimary" />

and be able to check the value of the radio button's checked value in jQuery, but my attempts like these don't return true/false.

if ($('[name=rbDate]').attr("Checked"))

if ($('[name=rbDate]').attr("Checked").val())

if ($('[name=rbDate]:checked').val())

A little help?

Margarita answered 8/10, 2009 at 23:48 Comment(0)
D
18

This is probably the easiest way to do it. The *= searches the whole id attribute for rbDate which takes care of the whole ASP.NET id mangling.

$('input[id*=rbDate]').is(":checked");
Dermato answered 8/10, 2009 at 23:52 Comment(7)
I don't get it. Why use the contains attribute filter when the ID is specific? Am I missing something?Tilefish
+1 From me, by the way. This answer is perfectly valid but if you don't have to it is fast to not have to match part of the id.Innes
@Tilefish - This is a rendered ASP.NET control which means that the rendered id will be mangled to include the id's of all the parent controls above this one.Innes
@Andrew Hare - my goodness, I'm just not good with ASP.NET. So confused am I. Sorry for the spamming.Tilefish
@Tilefish - LOL, no worries :)Innes
Thank you. This not only gave me what I wanted, but it was a good reminder about the name mangling.Margarita
That worked well and helped me. Another option is: $('#<%=rbDate.ClientID%>').is(":checked");Baronial
I
5

While ChaosPandion's answer will work it would be faster to wrap your RadioButtonList in a div like this:

<div id="dateWrapper">
    <asp:RadioButton 
        ID="rbDate" 
        runat="server" 
        Text="Date" 
        GroupName="grpPrimary" />
</div>

Then your jQuery code can be this simple:

var selected = $("#dateWrapper input:radio:checked");
Innes answered 8/10, 2009 at 23:58 Comment(2)
This is a good solution but in the majority of cases you won't even notice the speed difference.Dermato
Extra divs for simpler (but not shorter) jQuery isn't a great tradeoff for what I'm doing. Thanks for the idea, though!Margarita
M
3

INamingContainer adds a bunch of stuff to the beginning of the id of the actual html.

$('input[id$=rbDate]').attr('checked')

using the [id$=rbDate] bit on the selector tells jQuery that you want the input with an id that ends in rbDate

Now if you had a that you wanted to get the selected value of the entire list you might do something like

$('input[name$=rbDate]:checked').val()

which, were one of the items selected would return the value of the selected , or , in that radio button list.

Maxa answered 9/10, 2009 at 2:1 Comment(0)
C
0

Here is my JQuery solution that uses the asp.net ID:

var rbSelected =  $("#<%= rbDate.ClientID %>").is(":checked"); 
Cylindroid answered 23/9, 2015 at 2:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.