Selects Value

Select Elements have .value just like other form elements. Using the .value property you can assign and read the current selected items value. There's no need to use selectedIndex to locate the element in the options collection. What currently selected? and you can Set it to "option 3".

<select id="mySelect"> <option value="option_1">option 1</option> <option value="option_2">option 2</option> <option value="option_3">option 3</option> <option value="option_4">option 4</option> </select>
function test()
{
   alert( document.getElementById("mySelect").value );
}
function set()
{
   document.getElementById("mySelect").value = "option_3";
}

onchange

The select has an event onchange, this is fired each time the selected item is changed. The example below shows this event being used to alert the current value.

<select onchange="alert(this.value)"> <option value="option_1">option 1</option> <option value="option_2">option 2</option> <option value="option_3">option 3</option> <option value="option_4">option 4</option> </select>

Adding Options

It's also possible to change the items that are part of the select using createElement and appendChild. Add an option.

function AddOption( cText, cVal )
{
   var eOption = document.createElement("option");
   eOption.appendChild( document.createTextNode( cText ) );
   eOption.value = cVal;
   document.getElementById("mySelect3").appendChild( eOption );
}
Last Updated : 07/03/2006 @ 15:21