W3Schools.com

Select options Collection

Select Object Reference Select Object

Definition and Usage

The options collection returns an array of all the options in a dropdown list.

Note: There will be one array element for each <option> tag - starting at 0.

Syntax

selectObject.options

Properties

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

Methods

Method Description
[index] An integer that specifies the element to retrieve (starts at 0)
[add(element[,index])] Adds an option element into the collection at the specified index. If no index is specified, it inserts the option element at the end of the collection
item(index) Returns the element from the collection with the specified index
namedItem(name) Returns the element from the collection with the specified name (name or id attribute)
remove(index) Removes the element with the specified index from the collection


Browser Support

Internet Explorer Firefox Opera Google Chrome Safari

The options collection is supported in all major browsers.


Example

Example

Loop through all options in the dropdown list, and output the text:

<html>
<head>
<script type="text/javascript">
function displayResult()
{
var x=document.getElementById("mySelect");
var txt="All options: ";
var i;
for (i=0;i<x.length;i++)
{
txt=txt + "\n" + x.options[i].text;
}
alert(txt);
}
</script>
</head>
<body>

<form>
Select 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()">Loop through all options</button>

</body>
</html>

Try it yourself »


Examples

More Examples

Change the items in a dropdown list depending on the selected option in another dropdown list


Select Object Reference Select Object
WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$7.95/mo SEO Hosting
Premium Website Design
WEB BUILDING
XML Editor - Free Trial!
FREE Website BUILDER
Free Website Templates Free CSS Templates
Make Your Own Website
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE