Friday, May 29, 2009

Using onclick with ListItem within RadioButtonList Control

Below is a way to add an onclick event into the ListItems of a RadioButtonList Control:


Static RadioButtonList and ListItems within HTML
<asp:RadioButtonList id="citizenRbl" runat="server" RepeatDirection="Horizontal">
<asp:ListItem value="uscitizen" text="US Citizen"></asp:ListItem>
<asp:ListItem value="residentalien" text="Resident Alien"></asp:ListItem>
<asp:ListItem value="nonresidentalien" text="Non-Resident Alien"></asp:ListItem>
</asp:RadioButtonList>

Code Behind - add the onclick event to the parent control of the ListItems
citizenRbl.Attributes.Add("onclick", "CheckCitizenSelection('"+citizenRbl.ClientID+"')");

Javascript
<script language="Javascript">
function CheckCitizenSelection(rblID){
var rbl = document.getElementById(rblID);
var options = rbl.getElementsByTagName('input');
for(jj=0; jj<options.length; jj++)
{
  var cbox = options[jj];
  if(cbox.checked && cbox.value == "nonresidentalien"){
    alert('You choice was non-resident alien');
  }
}
}
</script>

No comments: