background
|
|
RiscOS
Risc OS Info
All you need to know about Risc OS and more.
More icon

Linux
Linux Support
A small area on the internet for Linux Support.
More icon
|
|
Up Image
Navigation
Search this Site
Enter your search terms

Site Breadcrumb - You are here
|
Multiple Selects

Multiple Selects

Putting the word "multiple" inside a select lets users select multiple options. If more than one option is chosen, the selectedIndex property of the select will contain the index number of the first option selected. How then do you get a list of all the options that a user has selected?

The way to do it is to check the selected property of each option object. For example, choose a few options below and hit the Select button. You can choose multiple options by holding down the control or shift key while you click.

Multiple list:

Here's how this works. The form looks like the forms from last page, except there's an onSubmit() in the form:

    
    <form name="form_1" onSubmit="reportMultiple(); return false;">
    
    
    
    <b>Multiple list:</b>
    
    <select name="list_1" size=4 multiple>
    
    <option>probiscus
    
    <option>spider
    
    <option>lemur
    
    <option>chimp
    
    <option>gorilla
    
    <option>orangutan
    
    </select>
    
    <p>
    
    <input type="submit" value="Select a few, then click me">
    
    </form>
    
    

When you click on the Submit button, the onSubmit event handler gets triggered and the reportMultiple() function is called. reportMultiple() is defined in the header and looks like this:

    
    function reportMultiple()
    
    {
    
    	var options_string = "";
    
    	var the_select = window.document.form_1.list_1;
    
    	for (loop=0; loop < the_select.options.length; loop++)
    
    	{
    
    		if (the_select.options[loop].selected == true)
    
    		{
    
    			 options_string += the_select.options[loop].text + " ";
    
    		}
    
    	}
    
    	alert("you selected: " + options_string);
    
    }
    
    

The first thing reportMultiple() does is declare the_select to refer to the select box and declare options_string to be blank. Then the function goes into a for loop, looping through all the options of the select. You can do this because the options property of a select form element is an array. You can find the number of options that are in a select element just like you can find out how long any array is.

Inside the for loop, we check the selected property of each option. If it's true, we add the text property of that option to options_string. When all the options have been checked, the loop exits and the alert box gets thrown up.

This looping through the options array and checking the selected property of each option is the only way to know which options were selected in a multiple-list select. I told you select elements were strange.

Back to the select element