views:

485

answers:

3

I have the following ASP.NET RadioButtonList:

<asp:RadioButtonList ID="rbl" runat="server">
    <asp:ListItem Text="Type1" Value="1" />
    <asp:ListItem Text="Type2" Value="2" />
</asp:RadioButtonList>

I would like to select an item in the list programmatically via a client-side jquery function like this (simplified version):

function BindWidget(widget) {
    // Type property of Widget is an int.
    $("#<%=rbl.ClientID%>").selectItemByValue(widget.Type);
}

Ideally, there is some function - in the above code I have proposed selectItemByValue - that selects an item in a RadioButtonList by a given value. Does jquery have a similar function built-in? If not, how should I go about implementing the desired functionality?

A: 
 function bindWidget(widget) {
   $('#<%-rbl.ClientId%> input:radio')
     .filter(function(btn) { return btn.value == widget.Type; })
     .attr('checked', true);
 }
Pointy
RadioButtonLists bind using <input /> rather than <option />, so you may want to do a binding more like $("input[id$='rbl'] input").filter()
ddango
Oh durr - sorry about that! Thanks @ddango!
Pointy
+1  A: 

Select it using:

$("#<%=rbl.ClientID%> input[value=" + widget.Type + "]")
Max Shawabkeh
this would work, though I opted to do a filter so that I didn't have to worry about potential "funny" characters in the "type" string value.
Pointy
I modified your suggestion to select the appropriate RadioButton emitted by the RadioButtonList; there is no "option" in the output like there is with a DropDownList. My actual ids are more verbose than "rbl", so this is not a problem. I like Pointy's idea of using a filter, but this approach seems to be more straightforward and it works correctly with the RadioButtonList.$("input[id*='rbl'][value='" + widget.Type + ']").attr("checked","checked");
mcliedtk
A: 

try this.

$('#<%=rbl.ClientID %>').find("input[value=" + widget.Type + "]").attr("checked", "checked");
SoftwareGeek