admin管理员组

文章数量:1415484

I need to get the ID of a dropdownlist (ASP.Net Control) So that I can tell if an item has been selected.

Right now I am trying to just write the count of the dropdownlist to an alert box as follows:

OnClientClick="alert(document.getElementID('<%=ListBox1.ClientID %>').options.length)

The error I get is 'document required.'

I need to get the ID of a dropdownlist (ASP.Net Control) So that I can tell if an item has been selected.

Right now I am trying to just write the count of the dropdownlist to an alert box as follows:

OnClientClick="alert(document.getElementID('<%=ListBox1.ClientID %>').options.length)

The error I get is 'document required.'

Share Improve this question asked May 14, 2009 at 17:41 EricEric 8,09819 gold badges101 silver badges131 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

First let's correct the getElementID in your code to getElementById:

OnClientClick="alert(document.getElementById('<%=ListBox1.ClientID %>').options.length);"

If you want to know which item is selected, use the selectedIndex property:

OnClientClick="alert(document.getElementById('<%=ListBox1.ClientID %>').selectedIndex);"

If you want the value of the option rather than the index, use the options collection with the index:

OnClientClick="var s=document.getElementById('<%=ListBox1.ClientID %>');alert(s.options[s.selectedIndex].value);"

Edit:
This would work if the control where you are trying to use it was not a server control, for example:

<input type="button" onclick="alert(document.getElementById('<%=ListBox1.ClientID %>').options.length);" />

As you have a server control, you can't use a script tag (<%= %>) inside the control. You have to set the property from code behind:

TheButton.OnClientClick = "alert(document.getElementById('" + ListBox1.ClientID + "').options.length);";

Pleas use document.getElementById instead of document.getElementId

My javascript is a bit rusty but can't you use the "this" keyword? something like:

OnClientClick="alert(this.options.length);"

本文标签: aspnetGetting Id of a net dropdownlist in javascript on client clickStack Overflow