Hi there,
In addition to Goran's reply, please find working snippet below:
-- begin aspx code --
<asp:DropDownList ID="ddlStatus" runat="server"
AutoPostBack="false" OnChange="SetDateFields()">
<asp:ListItem Text="Status1" Value="Value1"/>
<asp:ListItem Text="Status2" Value="Value2"/>
<asp:ListItem Text="Status3" Value="Value3"/>
</asp:DropDownList>
<script type="text/javascript">
function SetDateFields()
{
var statusList = document.getElementById('<%=ddlStatus.ClientID %>');
var selectedStatus = statusList.options[statusList.selectedIndex].text;
alert('selected status is : ' + selectedStatus);
}
</script>
-- end aspx code --
Note you have to use control.ClientID to get the valid ID (ClientID contains
all the parent controls ids - if i didnt use it and moved dropdown list to a
Panel control it'd stop work). You may be wondering why i put OnChange
attribute to drop down list declaration. This is allowed (even if you get a
warning from schema validation) and it's called 'expando'.
Hope it's clear now
Milosz
"C" wrote:
I have a dropdown list as below.
I add an onchnage attribute in my codebehind to call some Javascript.
I want to get the selected text from my dropdown. What am I doing wrong below?
<asp:DropDownList ID="ddlStatus" runat="server" />
In my codebehind
ddlStatus.Attributes["onchange"] = "javascript:SetDateFields();";
<script language="javascript" type="text/javascript">
function SetDateFields()
{
var statusList = document.getElementById("ddlStatus");
var selectedStatus = statusList.options[statusList.selectedIndex].value;
}
</script>