JavaScript program to get the selected value from a dropdown list of items

JavaScript program to get the selected value from a dropdown list of items:

In HTML, we can create a list of values in a dropdown using < select> component. We can provide a list of values using and user can select one among the list.

But to get the value once user selects one value, we need JavaScript. We can create one function in JavaScript and invoke that function once any value is selected.

In this post, we will create one HTML file that will show one dropdown to the user. This file will also include the JavaScript part with one method that will be invoked once the user selects one option in the list.

Create the project:

Create one HTML file example.html and change the content as below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script>
      function getSelectedOption() {
        document.getElementById("result").innerHTML = document.getElementById(
          "days"
        ).value;
      }
    </script>
  </head>
  <body>
    <select id="days" onchange="getSelectedOption()">
      <option value="0">Sun</option>
      <option value="1">Mon</option>
      <option value="2">Tues</option>
      <option value="3">Wed</option>
      <option value="4">Thurs</option>
      <option value="5">Fri</option>
      <option value="6">Sat</option>
    </select>
    <p id="result"></p>
  </body>
</html>

Explanation:

In this example,

  • select has different option with different values for each option. It will show a dropdown list of these options.
  • If you click on any of the value of these options, it will invoke the getSelectedOption JavaScript function.
  • This function, changes the innerHTML of the element of

    with id result. It assigns the value that is currently selected for days.

Open the file in a browser and if you select any option from the dropdown, it will change the text below that dropdown immediately.

javascript dropdown selection

You might also like: