views:

804

answers:

4

I am using ASP.NET with C#

I have a HTMLSelect element and i am attemping to call a javascript function when the index of the select is changed.

riskFrequencyDropDown is dynamically created in the C# code behind tried:

 riskFrequencyDropDown.Attributes.Add("onchange", "updateRiskFrequencyOfPointOnMap(" + riskFrequencyDropDown.ID.Substring(8) + "," + riskFrequencyDropDown.SelectedValue +");");

but it does not call the javascript function on my page. When i remove the parameters it works fine, but i need to pass these parameters to ensure proper functionality.

Any insight to this problem would be much appreciated

+3  A: 

Are your parameters numeric or alphanumeric? If they contain letters, you'll need to quote them in the javascript. Note the addition of the single quotes below.

riskFrequencyDropDown.Attributes.Add("onchange",
             "updateRiskFrequencyOfPointOnMap('"
                  + riskFrequencyDropDown.ID.Substring(8)
                  + "','"
                  + riskFrequencyDropDown.SelectedValue +"');");
tvanfosson
A: 

tvanfosson's response answers your question. Another option to consider (that might keep you from suffering from this again):

Author simpler javascript in your C#:

riskFrequencyDropDown.Attributes.Add("onchange",
             "updateRiskFrequencyOfPointOnMap(this);");

And then, inside the javascript function itself (that gets called on the onchange), get the values you need from the dropDown object:

function updateRiskFrequencyOfPointOnMap(dropDown) {
    var riskFrequencyId = dropDown.ID.Substring(8);
    var riskFrequencyValue = dropDown.SelectedValue;
    // etc
}

A less-obvious benefit to this design: if you ever change how you use the dropdown object (Substring(6) vs Substring(8), maybe), you don't have to change your C# -- you only have to change your javascript (and only in one place).

lance
A: 

I will suggest string.Format along with single quotes

riskFrequencyDropDown.Attributes.Add("onchange",string.Format("updateRiskFrequencyOfPointOnMap('{0}','{1}');",riskFrequencyDropDown.ID.Substring(8),riskFrequencyDropDown.SelectedValue ));
Raghav Khunger
A: 

I would suggest using Lance's answer. This is because sending the selected value at the time attribute.add gets called will mean that the onchange will use whatever the selected value was.

Lets say ddl contains ("One", "Two", "Three") and "One" is selected by default. Every time the ddl onchange gets called, the updateRiskFrequencyOfPointOnMap selected value parameter will contain "One" (even if "Three" is selected).

That is if that is your intended action is to do something with the selected value.

K3