views:

669

answers:

3

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?

+5  A: 

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");
ChaosPandion
I don't get it. Why use the *contains* attribute filter when the ID is specific? Am I missing something?
karim79
+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.
Andrew Hare
Is this a c#/.NET thing?
karim79
@karim79 - 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.
Andrew Hare
@Andrew Hare - my goodness, I'm just not good with ASP.NET. So confused am I. Sorry for the spamming.
karim79
@karim79 - LOL, no worries :)
Andrew Hare
Thank you. This not only gave me what I wanted, but it was a good reminder about the name mangling.
Dan Bailiff
+2  A: 

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");
Andrew Hare
This is a good solution but in the majority of cases you won't even notice the speed difference.
ChaosPandion
+1 Clean solution, intent is clear.
rick schott
Extra divs for simpler (but not shorter) jQuery isn't a great tradeoff for what I'm doing. Thanks for the idea, though!
Dan Bailiff
A: 

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.

Aaron