Javascript Form How to - Find the selected option








Question

We would like to know how to find the selected option.

Answer


<!--   www.java2  s.c o m-->

<html>
<head>
<script type="text/javascript" language="javascript">
function CheckOption(){
    var Selected = document.TestForm.PrizeChosen.selectedIndex;
    var SelectedOption = document.TestForm.PrizeChosen.options[Selected].value;
    document.writeln("The prize you have chosen is a " + SelectedOption);
}
</script>
</head>
<body>
<form name="TestForm" action="" onsubmit="CheckOption()">
Your Name:<input type="text" name="Name"/>
Your Gender:<input type="text" name="Gender"/>
 <select name="PrizeChosen">
  <option value="A">Choice A</option>
  <option value="B">Choice B</option>
  <option value="C">Choice C</option>
 </select>
 <input type="submit" value="Submit the form"/>
</form>
</body>
</html>

The code above is rendered as follows: