
Multiple Selects
Remember, 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.
Here's how this works. The form looks like the forms from last page,
except there's an onSubmit()
in the form:
<FORM NAME="form1"
onSubmit="reportMultiple();
return false;">
<B>Multiple list:</B>
<SELECT
NAME="list1"
SIZE="4"
MULTIPLE>
<OPTION>probiscus</OPTION>
<OPTION>spider</OPTION>
<OPTION>lemur</OPTION>
<OPTION>chimp</OPTION>
<OPTION>gorilla</OPTION>
<OPTION>orangutan</OPTION>
</SELECT>
<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 optString = "";
var theSelect = document.form1.list1;
for (loop = 0; loop <
theSelect.options.length; loop++)
{
//
if (theSelect.options[loop].selected
== true)
if (theSelect.options[loop].selected) {
optString += theSelect.options[loop].text + " ";
}
}
alert("you
selected: " + optString);
}
The first thing reportMultiple()
does is declare theSelect to refer to the
select box and declare optString 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 optString.
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. |