Categories:

JavaScript Kit > JavaScript Reference > Here

Select and Option objects

Last updated: November 19th, 2008

Form SELECT elements (<select>) within your form can be accessed and manipulated in JavaScript via the corresponding Select object. To access a SELECT element in JavaScript, use the syntax:

document.myform.selectname //where myform and selectname are names of your form/element.
document.myform.elements[i] //where i is the position of the select element within form
document.getElementById("selectid") //where "selectid" is the ID of the SELECT element on the page

Then, the options[] property of SELECT returns as a HTMLCollection every OPTION, for example:

document.getElementById("myselect").options[0] //accesses first option via options[]
document.getElementById("myselect").options[3] //accesses 4th option via options[]

Finally, each individual OPTION within SELECT is represented in JavaScript as a corresponding option object. This gives you access to an OPTION's actual value or text, among other things. For example:

document.getElementById("myselect").options[0].value //accesses value attribute of 1st option
document.getElementById("myselect").options[3].text //accesses text of 1st option

In summary, there is the select object in JavaScript to access a SELECT element, select.options[] property that contains each individual OPTION as a HTMLCollection, and finally, the option object that represents each OPTION itself in JavaScript.

Related Tutorials

Select Object

Events

Events Description
onBlur Code is fired whenever the focus is removed from the SELECT element.
onChange Code is fired whenever an OPTION within SELECT changes, through the user selecting another option. This event handler is commonly used to create a SELECT element that reacts as soon as the user has selected an option manually. Here's a SELECT menu that navigates to a particular site upon user selection:

Demo:

Example:

<form id="aform">
<select id="mymenu" size="1">
<option value="nothing" selected="selected">Select a site</option>
<option value="http://www.dynamicdrive.com">Dynamic Drive</option>
<option value="http://www.codingforums.com">Coding Forums</option>
<option value="http://www.cssdrive.com">CSS Drive</option>
</select>
</form>

<script type="text/javascript">

var selectmenu=document.getElementById("mymenu")
selectmenu.onchange=function(){ //run some code when "onchange" event fires
 var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu"
 if (chosenoption.value!="nothing"){
  window.open(chosenoption.value, "", "") //open target site (based on option's value attr) in new window
 }
}

</script>

onFocus Code is fired whenever the focus is set on the SELECT element.

Properties

Properties Description
disabled Boolean value that sets/ returns whether this SELECT element is disabled.
form References the form that contains the selection list in question.
length Returns the number of options in the SELECT element:

document.getElementById("mymenu").length //returns number of options

multiple Boolean that indicates whether this SELECT allows more than one option to be selected simultaneously.
name Reflects the name of the SELECT element (the name attribute).
options[] An HTMLCollection of Options objects containing each option within this SELECT element.
selectedIndex An integer that gets or sets the index of the selected option. If non is selected, -1 is returned. If multiple options are selected, it returns the index of the first selected option. When setting this property, the OPTION at the given position will be selected (while any previously selected option deselected).

The following example alerts the index number of the selected option within a SELECT element when the user makes a selection:

Demo:

<script type="text/javascript">
function alertselected(selectobj){
 alert(selectobj.selectedIndex)
}
</script>

<form id="someform">
<select id="sample" onChange="alertselected(this)">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="button" onClick="alertselected(document.getElementById('sample'))" value="alert" />
</form>

size An integer reflecting the number of OPTIONs being displayed at once within this SELECT element.
type A property available on all form elements, "type" returns the type of the calling form element. For SELECT, the two possible values are "select-one" or "select-multiple", depending on the type of selection list. The below code gives all SELECT elements in a particular form a CSS class of "selectclass":

<script type="text/javascript">

var myform=document.getElementById("someform")
for (var i=0; i<myform.elements.length; i++){ //loop through all form elements
 if (myform.elements[i].type=="select-one" || myform.elements[i].type=="select-multiple"){
  myform.elements[i].className="selectclass"
 }
}

</script>

Methods

Methods Description
add(newoption, beforeoption*)

*Important: beforeoption should be an object reference to an option except in IE, where it must be an integer representing the index of the option instead.

Dynamically adds a new OPTION to the SELECT element, where:
  • newoption: The new option to add, created using new Option().
  • beforeoption*: This parameter differs depending on the browser used:
    • In non IE browsers, an existing option (reference) within SELECT in which to add the new option following it. If null is entered, the new option is added at the very end.
    • In IE browsers (including IE8 beta2), an integer representing the position of the existing option to add the new option to (ie: 0=add following 1st element, 1=add following 2nd element etc). Leave this parameter out entirely to add the new option to the very end.

Due to the differences in the implementation of the 2nd parameter of add(), to make it cross browser, you can use try/catch to see which version the browser accepts. The 1st parameter newoption should simply be a new option created using new Option() (see Option object below for more info).

Example:

<form id="someform">

<select id="sample">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>

</form>

<script type="text/javascript">

var myselect=document.getElementById("sample")
try{
 myselect.add(new Option("New Last Option", "4"), null) //add new option to end of "sample"
 myselect.add(new Option("New First Option", "0"), myselect.options[0]) //add new option to beginning of "sample"
}
catch(e){ //in IE, try the below version instead of add()
 myselect.add(new Option("New Last Option", "4")) //add new option to end of "sample"
 myselect.add(new Option("New First Option", "0"), 0) //add new option to beginning of "sample"
}
</script>

results in the SELECT element becoming:

<select id="sample">
<option value="0">New First Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">New Last Option</option>
</select>

Note: An alternate, arguably simpler way of adding a new option to the SELECT element is simply to assign new Option() to one of the options within select.options[]. See Option object below for more info.

remove(optionindex) Removes an existing option within SELECT at the specified position, where 0=1st option, 1=2nd option etc, for example:

var myselect=document.getElementById("sample")
myselect.remove(myselect.length-1) //removes last option within SELECT

blur() Removes focus away from the selection list.
focus() Sets focus on the selection list.

Option object

The Option object represents each OPTION within a SELECT element as a JavaScript object.

Properties

Properties Description
defaultSelected A Boolean specifying whether this option is initially selected.
index Returns the index of this option within the select.options[] property.
selected Boolean that specifies whether this option is currently selected. The following looks through all OPTIONs within a SELECT to see which one is selected (assumes only 1 can be selected at any time):

<script type="text/javascript">

var myselect=document.getElementById("sample")
for (var i=0; i<myselect.options.length; i++){
 if (myselect.options[i].selected==true){
  alert("Selected Option's index: "+i)
  break
 }
}
</script>

text Specifies the text for the option.
value Specifies the value for the option.

The Option object allows you to add new options to your selection list using JavaScript. To dynamically create a new option, call its constructor function:

new Option([text], [value], [defaultSelected], [selected])

All parameters are optional:

  • text: String that sets the text of the option
  • value: String that sets the value attribute of the option
  • defaultSelected: Boolean that sets whether this option should be the default selected option (same effect as setting the defaultSelected attribute).
  • selected: Boolean that sets whether this option should be selected (same effect as setting the selected attribute).

While all paramters are optional, typically you'll want to define at least the first two parameter when calling new Option().

To add a new option to an existing SELECT element, just assign new Option() somewhere within select.options[] where you want the new option to be added. For example:

var myselect=document.getElementById("sample")
myselect.options[0]=new Option("New 1st option", "who") //replace 1st option with a new one
myselect.options[myselect.length]=new Option("Brand new option", "what") //add a new option to the end of SELECT

Notice how you can both replace an existing option, or add a new one to a SELECT element this way. It serves as an alternate method of adding/removing options to select.add() and select.remove(), with the main benefit being it works in all browsers out of the box, including in very old, non DOM2 legacy browsers. See Changing Select element options on the fly for more info.


Reference List

Right column

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info