|
Free
Javascript
Tutorials
|
|
|
JavaScript Tutorials Form Validation continued |
||||||||||||||||||||||
|
Using JavaScript to Validate a Drop Down Box
A drop down box on a form allows you to select one option among many. It looks like this:
Here's the HTML code for the above drop down box:
Notice the NAME of our Select box (as the drop down box is called in HTML world). The NAME we've chosen is s1. The name of our form is f1. So here's a function that gets which item the user selected: function GetSelectedItem() { len = document.f1.s1.length for (i = 0; i <
len; i++) { return chosen The code is similar to the check box code. We set the length of the select box (length is how many items in the list, minus 1 item): len = document.f1.s1.length Then inside the loop, we again access the index number of the SELECT object: document.f1.s1[i].selected So, s1[0] is the first item in the list, s1[1] the second item, s1[2] the third, and so on. Once the selected item has been detected, you access it's value property and pop it into a variable: chosen = document.f1.s1[i].value You can test out the script by selecting an item from the box below.
What we've done with this box is to add an event to the select box. The event calls the function: <SELECT NAME = s1 onChange = GetSelectedItem()> In the next part, we'll see how to get at which items have been selected in a list box. <--Back to the JavaScript Contents Page
|