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 page we add the control to the page:

<asp:RadioButtonList ID="grpLocation" runat="server" RepeatDirection="Horizontal" 

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");

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);

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: