1

This is in ASP.NET with C#. I am trying to programmatically call a Javascript function from a radiobuttonlist click event. I have created the radiobuttonlist and added a couple of list items inside. I have looked around a lot but have been unable to figure this out.

C# code:

RadioButtonList _rbList = new RadioButtonList();
_rbList.ID = r[0].ToString()+"Answer";
_rbList.RepeatDirection = RepeatDirection.Horizontal;
_rbList.Attributes.Add("onchange", "return answered();");

Javascript inside my .aspx:

<script type ="text/javascript">
function answered() {
    alert("I am an alert box!");
}
</script>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
shenn
  • 859
  • 4
  • 17
  • 47
  • When you say you're trying to call a javascript function from your C# event handler, do you mean you're trying to wire up a javascript event, or you actually want to run some javascript code when the page renders? – Gromer Oct 16 '12 at 21:46
  • 2
    You do know that using pure javascript and html (not using websockets or any other server-client push technology) that you can't have the server cause the client to do some random action, right? The client has to initiate all requests, or you have to setup some sort of a trigger (timer?) to operate for you. – jcolebrand Oct 16 '12 at 21:46
  • Forgive me, but isn't C# the server side language? I suppose you could use DWR to remote control the browser to a point...http://directwebremoting.org/dwr/index.html – Andrew Rhyne Oct 16 '12 at 21:46
  • As for wiring up the javascript to run on the change event, it might be easier to use the OnClientChange event, yes? – jcolebrand Oct 16 '12 at 21:47
  • 1
    If you do just want to inject some javascript to run, check out this Q/A: http://stackoverflow.com/questions/666519/difference-between-registerstartupscript-and-registerclientscriptblock – Gromer Oct 16 '12 at 21:47
  • Thanks Gromer, I will look into it. I have a very large .js file that has some functions I would like to call based on this radiobutton being clicked. – shenn Oct 16 '12 at 21:50

1 Answers1

2

You adding the onchange on the RadioButtonList...

Add it to the RadioButton inside of RadioButtonList and it will work, which in lower level speaking, adding attribute to the ListItem from Items from RadioButtonList, just one problem...

adding "onchange" attribute will be render a <span> containing the <input radio, pretty gross I know, try to add onclick instead, so the render can attach the attribute to the <input radio ,and do your magic on the javascript click, something like that:

RadioButtonList1.Items[0].Attributes.Add("onclick", "return answered();");
RollRoll
  • 8,133
  • 20
  • 76
  • 135
  • I was just looking this up, there's no OnClick or the like handlers for the RBL in MSDN: http://msdn.microsoft.com/en-us/library/ads2w011.aspx – jcolebrand Oct 16 '12 at 21:51