how to get the selected index of the asp:DropDownList control using javascript


I have an page, and I want to hide a div on the page when the index of the asp:DropDownList is 0 using javascript.

I know how to hide the div but I do need help on how to get the selected index of the asp:DropDownLists using javascript.

This is what I have in the javascript:

 function hideDiv() {
      var drpCampDock = document.getElementById('drpListCampaignDocketTemplate');
      var drpCampType = document.getElementById('drpCampaignType');

when it gets to this check it gives an error.

        if (drpCampDock.selectedIndex == 0) {
           document.getElementById('divBuilderMain').style.visibility = 'hidden';

The error I get is

Microsoft JScript runtime error: Object required

2 answers

I guess your problem is that the (client-side) ID of the rendered select element is not the same as the server-side ID of the asp:DropDownList (have a look at the HTML source code rendered in the browser to confirm this).

To get the correct client-side element, you'll have to use the following code:

var drpCampType = document.getElementById('<%= drpCampaignType.ClientID %>');

Alternatively you can change the ASP.NET markup to this and pass the div's ID and the dropdownlist's current selection to the javascript function:

<asp:DropDownList ... onchange="hideDiv('divBuilderMain', this.value)" />
function hideDiv(divId, ddlIndex)
  if (ddlIndex == 0) document.getElementById(divId).style.visibility = 'hidden';
User rating:

Thanks, your answer solved my problem!


I do this when I need selectedIndex:

var collx = document.getElementsByName("zmembertype");  
  for (ix = 0 ; ix < collx.length; ix++ ) {  
  if (collx[ix].checked)  
    temp = collx[ix].value;  

I think you need a loop ?

User rating:
But, maybe this answer is incorrect.

Post Answer