Javascript Form How to - Get selected option text








Question

We would like to know how to get selected option text.

Answer


<html> 
<head> 
<script type="text/javascript"> 
function seeColor(form) { <!--  w w w . ja  va  2 s  .co  m-->
    var newColor = (form.colorsList.options[form.colorsList.selectedIndex].text); 
    document.bgColor = newColor; 
} 
</script> 
</head> 
<body> 
<form> 
<select name="colorsList"> 
    <option selected="selected">Gray</option> 
    <option>Yellow</option> 
    <option>Black</option> 
    <option>Red</option> 
</select>
<input type="button" value="Change It" onclick="seeColor(this.form)" />
</form> 
</body> 
</html>

The code above is rendered as follows: