Net list id in javascript on client.

I need to get the ID of the dropdown (ASP.Net Control) so that I can determine if an item has been selected.

I am currently trying to simply write a dropdown counter in the alert box like this:

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

      

The error I am getting is "required document".

+1


a source to share


3 answers


First, adjust 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 property selectedIndex

:

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

      

If you want a parameter value rather than an index, use the indexed options collection:



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

      

Edit:
This will work if the control you are trying to use it in is not server-side, e.g .:

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

      

Since you have a server control, you cannot use the script (<% =%>) tag inside the control. You have to set the property from code:

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

      

+2


a source


To use declaration document.getElementById instead of document.getElementId



0


a source


My javascript is a little rusty, but can't you use the "this" keyword? sort of:

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

      

0


a source







All Articles