Javascript Form How to - Get selection option text








Question

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

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function fun(e) {<!--from   w ww .  j  a  v a 2s . co  m-->
    document.getElementById('caption').innerHTML = e.options[e.selectedIndex].text
}

</script>
</head>
<body>
  <select onchange=fun(this)>
    <option id="apple">Apple</option>
    <option id="orange">Orange</option>
    <option id="pineapple">Pineapple</option>
    <option id="banana">Banana</option>
  </select>
  <p id="caption"></p>
</body>
</html>

The code above is rendered as follows: