views:

871

answers:

4

Is there a way to call a javascript function when the selectedIndex of a select input has been changed?

Using this code in the c# code behind file

riskSeverityDropDown.SelectedValue = Convert.ToString(planRisk.Severity);
riskSeverityDropDown.SelectedIndexChanged += new EventHandler(riskSeverityDropDown_SelectedIndexChanged);
riskSeverityDropDown.AutoPostBack = true;

want to change something else on the page with javascript when the index is changed.

Any help would be much appreciated. Thanks in advance

A: 

You want to add an attribute to that drop down called "onchange" and set it to call a JavaScript method of your choosing.

Jon
This won't work- as long as AutoPostBack is also true any changes his javascript makes will be lost right away.
Joel Coehoorn
+1  A: 

Simply add an onchange to your asp:dropdownlist.

<asp:DropDownList ID="riskSeverityDropdown"
                  AutoPostBack="True"
                  SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged"
                  onChange="functionName()"
                  runat="server" />

or to do this from codebehind use:

riskSeverityDropdown.Attributes["onchange"] = "functionName()";
Zyphrax
This won't work- as long as AutoPostBack is also true any changes his javascript makes will be lost right away.
Joel Coehoorn
+5  A: 

You're already going to server code (AutoPostBack is true), which means you're going to rebuild the entire page anyway. Running javascript at this point would be a little silly, because any changes you make to the DOM will be lost and any ajax requests you want to send can instead be handled by normal server code. If you really want to do this, you can just register the script to run when the page loads after the postback.

On the other hand, if you can do this without any server code at all then set AutoPostBack to false and the basic html select control has a nice onchange event you can handle.

Joel Coehoorn
A: 

Use JQuery. It exposes a rich set of events that you can use to code against practically anything in a uniform manner. It is also quite easy to learn, compact, and popular.

In short you can't go wrong if you use JQuery. It is meant to solve problems like this well.

Cyril Gupta