Free Javascript Tutorials

home

JavaScript Tutorials

Form Validation continued

 
Our quick javascript links
Little Programmes
 
 
 
 
 
 

 

Using JavaScript to Validate a List Box

 

A form element closely related to the Select element is the Multiple select. This time, the elements is a list box where you can select more than one item. You select more than one item by holding down the Ctrl key on your keyboard and then clicking items with your left mouse button. Here's what they look like:

To get which items have been selected, we can use the same code we used for the drop down list. The only difference is the line inside the if statement:

function GetSelectedItem() {

len = document.f1.s1.length
i = 0
chosen = ""

for (i = 0; i < len; i++) {
if (document.f1.s1[i].selected) {
chosen = chosen + document.f1.s1[i].value + "\n"
}
}

return chosen
}

The main thing that's changed is this line:

chosen = chosen + document.f1.s1[i].value + "\n"

And the only thing we're doing different is adding the selected item to whatever is already inside the variable called chosen and we've added the new line character to the end. Also changed is chosen = "" insted of "none",

As a matter of interest, the HTML code for a Multiple select list box is this:

<SELECT NAME = s1 size = 5 multiple>

SIZE is how many items in the list (starting at 1). Then you just add the word multiple. The rest of the HTML code is the same as the SELECT box.

You can test out the script by selecting a few items from the box below. Then click the button.

In the final part of the Form Validation section, we'll take a look at how to validate Radio Buttons.

Move on to the Next Part-->

<--Back to the JavaScript Contents Page