Monday, December 29, 2008

Javascript : Accessing ASP.NET RadioButtonList or CheckBoxList in Javascript

here is a sample radio button list

<asp:radiobuttonlist id="RadioButtonList1" runat="server">
<asp:listitem value="1">One</asp:listitem>
<asp:listitem value="2">Two</asp:listitem>
<asp:listitem value="3">Three</asp:listitem>
</asp:radiobuttonlist>

here is a sample script to check atleast one item should be checked

function validateRadio()
{
var count = <%=RadioButtonList1.Items.Count %>;
var id = "<%=RadioButtonList1.ClientID%>";
var checked = false;
for(i=0;i<count;i++)
{
if(document.getElementById(id+"_"+i.toString()).checked==true)
{
checked = true;
break;
}
}
return checked;
}

RadioButtonList and CheckBoxList works exactly same way, so go ahead and use the same funtion for the CheckBoxList also, and you can create as many validations as you think of! happy coding :)

3 comments:

  1. Nice post. First one I found that actually works ( out of countless posts that would have you think they worked).

    The only downside I can think of is that this code relies on the exact format that asp.net emits into the rendered client code at run time. Since there is no formal garantee that this format will never change, its a risk.

    Still works though, good job!

    ReplyDelete
  2. thanks for the appriciation,
    as per my knowledge asp.net generates ids separated by underscore(_) and names separated by ($), so generally this always worked for me. please tell me more about the client code (ClientID) generation of the control in asp.net if possible.
    regards

    ReplyDelete
  3. What I've just found is this
    http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx

    Assuming the feature does make it into the asp.net release, we shall have to take this into consideration in client side scripts.

    Cordially,
    Gabe Levy

    ReplyDelete

Please add your valuable comments about this post if it helped you. Thanks