How to Make JavaScript Dropdown List


Introduction:

Drop down menus are nowadays integrated with functions which enhance the web usage. In this tutorial, we will learn how to make javascript dropdown list.

Step 1 – Enter the code for the List

After the body and html tags, start with

tag. Give a title to the drop down menu. For the purpose of this tutorial, we want to make a drop down list from where people can choose their favorite sport.

Next, open up the select tag and give it an id. Then give a function name for changing the list. For that, we have used the “on change” keyword and specified the function as favsports(). Just ignore the function for now as we will define its working later on.

Once done with that, insert the different options for your drop down menu. Enclose these options between option tags. Once completed, close the select tag.

Next, specify a narration for the output in the p tag. Choose the character type as text. For the purpose of this tutorial, we will name it as favorite and will specify its size as twenty. With that done, close the form tag.

Insert the code

Step 2 – Coding for the function

Now open the script tag right above the body tag. Right beneath the script tag, we will begin with our function definition. In order to do so, specify your function name along with the function keyword, insert parenthesis and then start with the actual definition enclosed in curly brackets.

In the function body, we will first explain the chosen element of menu. We are using a function of “get element by id” and specifying the element within the parameters from which we have to pick up the value, which is of course our javascript dropdown menu. It has already been named as mylist earlier.

The next line is about displaying the selected option in a text box. For this purpose, we are using the “selected index” function and then passing the value to the text box, which we have named as favorite, with the “get element by id” method.

Once you are done, close the script tag and then save the file as html document.

Coding for java Script functions

Step 3 – Open the file

Now open up any browser and open the file that you just saved. The javascript dropdown list that you created will be available there. Simply choose any option from the dropdown list and it will appear in the text field right below.

In this manner, you can create javascript dropdown list.

View the Java Script menu