views:

1795

answers:

3

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.'

A: 

Pleas use document.getElementById instead of document.getElementId

Vikram
+1  A: 

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);";
Guffa
Still getting Object Required.
Eric
I see. It's the <%= %> script tag that is the matter. I edited the answer.
Guffa
A: 

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

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