Dropdown Menu JavaScript Tutorial
A drop-down menu makes it possible to display large amounts of data in small amount of space. Web developers use these menus to hold shopping cart products, geographical locations and a variety of other items. Site visitors click an arrow next to a drop-down menu to view its contents. You create a drop-down menu using HTML. After your webpage is loaded, you can modify the menu by calling JavaScript functions. You may not need to alter drop-down menus often, but if the need arises, JavaScript can assist you.
- Difficulty:
- Moderately Easy
Instructions
-
-
1
Create a new HTML document.
-
2
Add a drop-down menu and two buttons to the body section as shown below:
<select name="myDropdown' id='myDropdown'>
<option value='20'>20</option>
<option value='30'>30</option>
</select>The "select" tag creates the drop-down menu. Each "option" tag defines an item within the drop-down menu. You can add as many option tags as you need. This drop-down menu will display 20 and 30 when you open the menu. Add additional items by adding additional option tags. The value property determines the text that you see when you open the menu.
-
3
Add the following code below the drop-down menu:
< br /><input id="Add" type="button" value="Add" onclick="demo('ADD')" /><br />
<input id="Delete" type="button" value="Delete" onclick="demo('DELETE')" /> -
4
Add this JavaScript function to the "script" section of the HTML document:
function demo(action) {var tmpList = document.getElementById("myDropdown");
var tmpOption = document.createElement("option");if (action == "ADD") {
tmpOption.text = "http://www.google.com";
tmpOption.value = "Go to this site";
tmpList.options.add(tmpOption);
}else if (action == "DELETE") {
var listCount = tmpList.length-1;
if (listCount > 0) tmpList.options.remove(listCount);
}
}This function will add and delete an item from the drop-down menu. Modify a drop-down menu by obtaining its ID and executing the "options.add" JavaScript command as shown in the code. Drop-down menus are not "strongly typed." This means that you can mix different types of data in them. In this example, we combined a URL and numbers strings.
-
5
Upload the HTML document to your browser and click the buttons. The "Add" button will add a URL item to the menu. The "Delete" button will delete the last item in the menu. Deletion from a drop-down menu might be useful when you need to remove an item from a product catalog menu that a site visitor has added to a shopping cart. You can delete any items in a drop-down menu by specifying their location in the menu.
-
1
Tips & Warnings
Do not try to call the JavaScript functions until the page load event has completed. HTML objects are not accessible until that event occurs. See the Resources section for links to JavaScript tutorials.
Related Searches
References
Resources
- Photo Credit typing image by PD-Images.com from Fotolia.com