"Mufasa" <jb@nowhere.comwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
How can I make an asp:radiobutton where when the user selects it it runs
javascript code? I've tried doing the following but it doesn't seem to
work:
arbLogoAttached.Attributes.Add("OnCheckedChanged",
"javascript:RadioClicked();");
But that doesn't seem to work. And it doesn't seem to put the onclick or
oncheckedchanged on the input itself - it's putting it on a span around
the object.
Anybody have any thoughts?
When you add attributes to controls which will render as client-side HTML,
you can only add those attributes which actually exist for the type of
control to which you're trying to add them. Specifically, in this case, an
<asp:RadioButton ...webcontrol renders as an <input type="radio".....>
object, which doesn't have an "OnCheckedChanged" method, so trying to wire
one up server-side will do nothing at all, as you've discovered.
Fortunately, what you're looking for is extremely simple:
protected void Page_Load(object sender, EventArgs e)
{
opt1.Attributes.Add("onclick", "radioButtons(this);");
opt2.Attributes.Add("onclick", "radioButtons(this);");
opt3.Attributes.Add("onclick", "radioButtons(this);");
}
<head>
<script type="text/javascript">
var optSelected;
function radioButtons(pobjButton)
{
if (pobjButton.id == optSelected) {return;}
optSelected = pobjButton.id;
//alert('You selected ' + pobjButton.value);
// your code goes here
}
</script>
</head>
<asp:RadioButton ID="opt1" runat="server" Text="Option 1"
GroupName="grpTest" /><br />
<asp:RadioButton ID="opt2" runat="server" Text="Option 2"
GroupName="grpTest" /><br />
<asp:RadioButton ID="opt3" runat="server" Text="Option 3"
GroupName="grpTest" />
--
Mark Rae
ASP.NET MVP
http://www.markrae.net