How to Get Selected Value from Dropdown in Javascript
In this tutorial, you will learn how to get selected value from dropdown in javascript. A dropdown list contains a bunch of options and based on the selected option, we can execute a certain piece of code. This can only happen efficiently if you know the right way to do it.
A good example can be a dropdown list that contains options like Animals, Books, and Movies. Based on the user selection, we will display a list of animals, books, or movies. The first step would be to get the value of the selected option and make a request to the server. The server will then return the data and we will display it to the user.
In the following example, we have a dropdown list with a bunch of options. We will select a random option from the list and display its value on the screen. Please have a look over the code example and the steps given below.
HTML & CSS
- We have a few elements in the HTML file and that includes
div
,select
,option
,h2
, andh3
. - The
div
element with astyle
attribute is just a wrapper for the rest of the elements. - The
select
element has 5 options. The first option with text“Select”
is default withhidden
anddisabled
attributes. - The inner text for the
h2
element is“Result”
. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="container" style="text-align: center;"> <h3>Select Programming Language</h3> <select> <option disabled hidden selected>Select</option> <option value="javascript">Javascript</option> <option value="angular">Angular</option> <option value="xyz">React</option> <option value="csharp">C#</option> </select> <h2>Result</h2> </div> <script src="script.js"></script> </body> </html>
Javascript
- We have selected
select
element andh2
element usingdocument.querySelector()
and stored them inselection
andresult
variables respectively. - We have attached a
change
event listener to theselect
element. - In the event handler function, we are using
selectedIndex
property to get the index of the currently selected option. - The
selection.options
returns an array. In an array, we can get an item by using its index. We are using the value returned byselectedIndex
here and getting the value of the selected option. - The selected option value will be displayed in the
h1
element using theinnerText
property.
let selection = document.querySelector('select'); let result = document.querySelector('h2'); selection.addEventListener('change', () => { result.innerText = selection.options[selection.selectedIndex].value; console.log(selection.selectedIndex); });