Select options Collection - Javascript DOM HTML Element

Javascript examples for DOM HTML Element:Select

Description

The options collection returns all <option> elements in a drop-down list sorted as they appear in the source code.

Properties

Property Description
lengthnumber of <option> elements in the collection
selectedIndex Sets or returns the index of the selected <option> element (starts at 0)

Methods

MethodDescription
[index] <option> element with the specified index (starts at 0).
[add(option[,index])] Adds an <option> element into the collection at the specified index. If index is not specified, it inserts the option at the end of the collection
item(index) <option> element with the specified index (starts at 0).
namedItem(id) <option> element with the specified id.
remove(index) Removes the <option> element with the specified index from the collection

Return Value:

An HTMLOptionsCollection Object, representing all <option> elements in the <select> element.

The following code shows how to Find out how many options there are in a specific drop-down list:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<form>
  <select id="mySelect" size="4">
    <option>Apple</option>
    <option>Orange</option>
    <option>Pineapple</option>
    <option>Banana</option>
  </select>
</form>/* w w w.  jav a  2 s .c  o m*/

<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").options.length;
    document.getElementById("demo").innerHTML = "Found " + x + " options in the list.";
}
</script>

</body>
</html>

Related Tutorials