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

Freshness Warning
This post is more than 3 years old. Please bear in mind its age when reading.

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:

<script language=javascript type="text/javascript">
     function DoSomething(object)
     {
     alert("You clicked on :" + object);
     }
</script>

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

I'm running the 39th BMW Berlin Marathon on 30th September 2012 for the British Lung Foundation, who are currently funding research on the prevention of lung damage in COPD and many other areas related to lung disease.

I'm participating with my sister Claire Kewney and, on behalf of the charity, would appreciate even the smallest donation. My own JustGiving page is here, our team page is here.

if you're in the UK, you can also donate using your mobile phone by texting NKEW82 £5 (or any amount) to 70070. Your donation will be appreciated!

Comments

  1. It's function perfect. Thanks
Your Comment
Your Name
E-mail Address (This won't be published)
Website URL

You can manage your Kewney.com account by logging in. [ Log On ]