Welcome to Bucaro TecHelp!

Bucaro TecHelp
HTTPS Encryption not required because no account numbers or
personal information is ever requested or accepted by this site

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Java Script to Get Selected Item from Drop-down Select List

An HTML Select list is a form control 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.

<form>
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</form>

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>

function grabSelection()
{
  alert(document.myForm.mySelect.selectedIndex);
}

</script>

<form name="myForm">
<select name="mySelect" onchange="grabSelection()">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</form>

Setting the Default Selected Item

You can set a default selected item by using the default attribute in one of the option elements as shown below.

<script language="JavaScript">

function getForm(form)
{
 alert(form.mySelect.options[form.mySelect.selectedIndex].value);
}

</script>

<form name="myForm">
<select name="mySelect">
<option value="Bread">Bread</option>
<option value="Coffee">Coffee</option>
<option value="Salad" selected>Salad</option>
<option value="Soup">Soup</option>
</select>
<input type="button" value="Get Selection" onclick="getForm(this.form)">
</form>

A select list is a form control, and there may be other controls in the form. In that case, you use a form button to pass the entire form. Note in the code above that I used the button's onclick event to execute the getForm function.

More Java Script Code:
• Java Script Code to Factor Numbers
• Calculators for Your Website : Fahrenheit to Celsius Converter
• Regular Expressions Boundaries
• How to Place Image on HTML5 Canvas
• Calculators for Your Web Site : Loan Payment Calculator
• Easy Slide Show Code with Mouseover Pause
• How Far Did the User Scroll?
• Calculators for Your Website : Decimal to Hexidecimal Converter
• Java Script to Dynamically Add, Remove, and Change Items in a Select List
• Easy Expanding Menu Code

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro



Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2020 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268