How to Use a Variable Menu List in JavaScript
A drop-down menu is an expandable list of text entries on a Web page that users can select from with their mouse. A user's selection might be submitted as part of a form or used to trigger JavaScript code for more dynamic effects and functionality. JavaScript can also be used to dynamically alter the contents of a drop-down menu after the page is loaded, so you can reconfigure the menu options available to the user on-the-fly.
Instructions
-
-
1
Insert the following code between the "head" tags of your HTML document:
<script type="text/javascript">
function addMenuItem(menuObj,itemname,index){
menuObj = document.getElementById(menuObj);
var newItem=document.createElement("option");
newItem.text=itemname;
menuObj.add(newItem,menuObj.options[index]);
}
function removeMenuItem(menuObj,index){
menuObj = document.getElementById(menuObj);
menuObj.remove(index);
}
</script>
These two functions add and remove items from a drop-down menu, respectively. The menu is identified by its unique "id" attribute. The "index" variable is used to specify a location in the menu: the first item in a menu has the index value "0," the next "1" and so on.
-
2
Create a drop-down menu in the body of your HTML document with code like this:
<select id="menu1">
<option>Menu Item 1</option>
<option>Menu Item 2</option>
<option>Menu Item 3</option>
</select>
If you use multiple drop-down menus in one page, give each "select" tag a unique "id" attribute.
-
-
3
Add the following code to the body of your HTML document to test the JavaScript functions on the menu you created:
<input id="input" type="text" />
<input type="button" value="Add Menu Item" onClick="addMenuItem('menu1',document.getElementById('input').value)" />
<input type="button" value="Remove Menu Item #" onClick="removeMenuItem('menu1',parseInt(document.getElementById('input').value));" />
-
4
Save the page and load it in a Web browser. Type something into the text field and click "Add Menu Item." Click the drop-down menu and see that your item has been added. Type the number 0 into the field and click "Remove Menu Item #." The first item is removed from the menu.
-
1
Tips & Warnings
Pass a third numerical argument to "addMenuItem" to insert the new item at a particular index location in the menu, instead of at the end.
- Photo Credit Hemera Technologies/Photos.com/Getty Images