DropDownList (or) Select

Content:

  1. Clear items from DropDownList
  2. Get selected index from DropDownList
  3. Get selected text from DropDownList
  4. Get selected value from DropDownList
  5. Set DropDownList selected value based on display text
  6. Set DropDownList selected value based on display value

1. Clear items from DropDownList:

document.getElementById('ddlRole').options.length = 0;

2. Get selected index from DropDownList:

var ddl = document.getElementById('ddlRole');
alert('Selected Index is: ' + ddl.options.selectedIndex);

3. Get selected text from DropDownList:

var ddl = document.getElementById('ddlRole');
alert(ddl.options[ddl.options.selectedIndex].text);

4. Get selected value from DropDownList:

var ddl = document.getElementById('ddlRole');
alert(ddl.options[ddl.options.selectedIndex].value);

5. Set DropDownList value based on display text:

var ddl = document.getElementById('ddlRole');

// Now set dropdown selected option to 'Admin'.
setSelectedIndexByText(ddl, 'Admin');

// This function is used to set the dropdown index based on text.
function setSelectedIndexByText(d, t){
    for(var i = 0; i < d.options.length; i++){
        if(d.options[i].text == t){
            d.options[i].selected = true;
            return;
        }
    }
}

6. Set DropDownList value based on value:

var ddl = document.getElementById('ddlRole');

// Now set dropdown value to 2.
setSelectedIndexByValue(ddl, 2);

// This function is used to set the dropdown index based on value.
function setSelectedIndexByValue(d, v){
    for(var i = 0; i < d.options.length; i++){
        if(d.options[i].value == v){
            d.options[i].selected = true;
            return;
        }
    }
}
  • Updated
    Jan 07, 2015
  • Views
    2,238