Welcome to Bucaro TecHelp!

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

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

Allowing Multiple Selections 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. You can allow the user to select multiple items in the list by setting its multiple attribute. Code for a select list with its multiple attribute set is shown below.

<form>
<select name="mySelect" size="7" multiple="multiple">
<option value="Bread">Bread</option>
<option value="Coffee">Coffee</option>
<option value="Fruit">Fruit</option>
<option value="Pie">Pie</option>
<option value="Salad">Salad</option>
<option value="Soup">Soup</option>
<option value="Wine">Wine</option>
</select>
<input type="button" value="Get Selection" 
	onclick="grabSelection(this.form.mySelect)">
</form>

The user can select multiple items in the list by pressing the Keyboard Ctrl key, or by selecting an item and pressing and holding the Shift key while selecting another item. This second method allows the user to select a range of items from the list.

When the user selects items in a select list, the selected property of the option is set. The select list options are an array with indexes that start at 0 for the first option. The code below shows one way to access the indexes of the options set to selected, and then to access the value property of those options.

<script type="text/javascript">

function grabSelection(list)
{
  var strMsg = "";

  for(var i = 0; i < list.length; i++)
  {
    if(list.options[i].selected)
    {
      strMsg = strMsg + list.options[i].value + "\n";
    }
  }
  alert(strMsg);
}      
</script>

A select list is a form control, in this code the onclick event of the button passes the select list to the grabSelection function. There may be other controls in the form. In that case, you use the form button to pass the entire form.

More Java Script Code:
• JavaScript Code to Save and Load a Table Using HTML5 Web Storage
• Code to Drag and Drop an Image Anywhere on a Webpage
• How to Use HTML5 canvas arc and arcTo Functions
• Easy Graph Generating Code
• Use JavaScript parseInt() and parseFloat() to Convert Strings to Numbers
• Learn JavaScript Visually
• HTML5 Canvas JavaScript Code to a Draw Bezier Curve
• Basic State Machines
• JavaScript Code to Display Wait Cursor While Image Loads
• Easy Slide Show Code With Linked Slides

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-2018 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268