Adding a Javascript onclick event to a Radio Button List Item on DataBound

This is very straightforward and can add some extra functionality to your forms in the sense of if this value is selected show that div.

Within the asp.net page we add the control to the page:

<asp:RadioButtonList ID="grpLocation" runat="server" RepeatDirection="Horizontal" 
OnDataBound="grpLocation_onDataBound">
</asp:RadioButtonList>

Within the code behind we add some listitems to the Radio button list:

ListItem A = new ListItem("Edinburgh", "Edinburgh");
ListItem B = new ListItem("Glasgow", "Glasgow");
ListItem C = new ListItem("Aberdeen", "Aberdeen");
ListItem D = new ListItem("Scotland", "Scotland");
grpLocation.Items.Add(A);
grpLocation.Items.Add(B);
grpLocation.Items.Add(C);
grpLocation.Items.Add(D); 
grpLocation.DataBind();

In the code behind we add the following code to the grpLocation_onDataBound event:

 RadioButtonList rbl = (RadioButtonList)sender;
        foreach (ListItem li in rbl.Items)
        {
            li.Attributes.Add("onclick", "javascript:ShowExt('" + li.Value + "')");
        }

What the above code is saying is add the attribute “onclick” to each list item within the RadioButtonList with a value of “javascript:ShowExt(‘value’)”.

For the above example to work we’ll also need to add the javascript function “ShowExt” to the page:

 <script language=javascript type="text/javascript">
    function ShowExt(object)
    {
    alert("Value Clicked :" + object);
    }
    </script>

What the above code will do is show an alert box with the value of the radio item. Short, simple and sweet.

Click here to see a live demo

related posts: