Adding JavaScript onclick event to Radio Button List items in VB.net

This is a very simple post covering how to capture of a Radio Button List item value using the JavaScript onclick event handler. I’ll start by assuming you already have the Radio Button List on your page and bound to a data source as follows:

<asp:RadioButtonList ID="rblItems" runat="server" DataSourceID="MyDataSource" DataTextField="MyDataTextField" DataValueField="MyDataValueField"></asp:RadioButtonList>

In your codebehind file, add the following to the DataBound event of the rblItems control:

Private Sub rblItems_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblItems.DataBound Dim rbl As RadioButtonList = DirectCast(sender, RadioButtonList) For Each li As ListItem In rbl.Items li.Attributes.Add("onclick", "javascript:DoSomething('" + li.Value + "')") Next End Sub

Finally, add the JavaScript ‘DoSomething’ method that will be referenced when the list items is pressed by adding this to your page:

     function DoSomething(object)     {     alert("You clicked on :" + object);     }

This code will show a JavaScript popup window with the value of the clicked Radio Button List item.

Leave a Reply