The Select list is one of the most useful controls provided by HTML. This article demonstrates the incredible flexibility of the Select list and provides you with example code to do almost you could want with a Select list.
Welcome to Bucaro TecHelp!

Welcome to Bucaro TecHelp!
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

[About BTH]  [User Agreement]  [Privacy Policy]  [Site Map]  [Contact Form]  [Advertise on BTH]  [News Feed]


HTML Select List Basics

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>

Web Design Sections

RSS Feed RSS Feed

Google Reader or Homepage
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online

Add to My AOL
Add to Technorati Favorites!

HTML Design


[Site User Agreement]  [Advertise on This site]  [Search This Site]  [Contact Form]
Copyright©2001-2010 Bucaro TecHelp P.O.Box 18952 Fountain Hills, AZ 85269