|
HTML Select List Basics
By Stephen Bucaro
The Select list is one of the most useful controls provided by HTML.
An HTML Select list is used to create a drop-down list of items from which
the user can select. Each item in a select list is defined by an option element.
The most basic code for a select list is shown below.
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
We can access the select list with simple Java Script code, allowing us to
control the appearance of the list, get the selected item or items, add items,
remove items, or replace items in the select list. In this article, I'll provide
easy Java Script code to do all that and more.
Using a Select List
When the user selects one of the items in a select list, an onchange
event is triggered. The selectedIndex property will then contain the
index of the item that the user selected. Select list option indexes start with
0 for the first item. The code below shows one way to access the index of the
item that the user selected.
<script language="JavaScript">
function getSelection()
{
alert(document.myForm.mySelect.selectedIndex);
}
</script>
<form name="myForm">
<select name="mySelect" onchange="getSelection()">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</form>
Sometimes you'll want to work with the value of a list item rather than its
index. In that case you can assign a value to the value attribute of each
option element. In the code shown below we pass the list object to a function
which displays the value of the selected option.
<script language="JavaScript">
function getSelection(list)
{
alert(list.options[list.selectedIndex].value);
}
</script>
<form name="myForm">
<select name="mySelect" onchange="getSelection(this)">
<option value="Item 1">Item 1</option>
<option value="Item 2">Item 2</option>
<option value="Item 3">Item 3</option>
</select>
</form>
|