Easy Tutorial
❮ Event Onoffline Prop Area Nohref ❯

Select options Collection


Definition and Usage

The options collection returns an array of all <option> elements in a <select> element.

Note: Each element in the array corresponds to an <option> tag, starting from 0.

Syntax

Properties

Property Description
length Returns the number of option elements in the collection
selectedIndex Sets or returns the index of the selected option in the select object (starting from 0)

Methods

Method Description
[ index] Specifies the element index numerically (starting from 0)
[add( element[, index])] Adds an option element to the collection
item( index) Returns the element in the collection by numeric index
namedItem( name) Returns the element in the collection by name
remove( index) Removes the element from the collection

Browser Support

All major browsers support the options collection.


Example

Loop through all options in a dropdown list:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>tutorialpro.org(tutorialpro.org)</title>
<script>
function displayResult(){
    var x=document.getElementById("mySelect");
    var txt="All options: ";
    var i;
    for (i=0;i&lt;x.length;i++){
        txt=txt + "\n" + x.options[i].text;
    }
    alert(txt);
}
</script>
</head>
<body>

<form>
Your favorite fruit:
<select id="mySelect">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
</select>
</form>
<button type="button" onclick="displayResult()">Display text of all options</button>

</body>
</html>

More Examples

Modify the options of the current dropdown menu based on the selected option of another dropdown menu.


❮ Event Onoffline Prop Area Nohref ❯