Jump to content

Validating Drop-Down Lists

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Blue Indian

Blue Indian

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
How do you validate whether a drop-down list has an item selected? I figured the selectedIndex would return -1 if no item was selected, so I tried this:

if (document.getElementById('Roast').selectedIndex ==  -1){

		document.getElementById("roastError").innerHTML = "You must select a roast.";

	}

	else{

		document.getElementById("roastError").innerHTML = "";

	}


#2
dbug

dbug

    Programmer

  • Members
  • PipPipPipPip
  • 155 posts
In HTML, a drop-down list (using select tag) will always have an item selected (by default it's the first one). If you want to add the possibility to leave the combo empty, the first option of the select must contain a blank value.

The only case in which you may have no item selected is when the list of options is empty. In this case selectedIndex is -1.

#3
Blue Indian

Blue Indian

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
The solution then is to make your first option with a value such as "none" and text such as "--Choose One--".

Then with javaScript, you can check to see if the user has made a selection by comparing selectedIndex to 0 since that will be the value when the user does not make a selection.

Below is an example to illustrate:

//HTML for selecting what kind of coffee roast

<select name='RoastDropDown' id='RoastDropDown'>

  	<option value="none">Choose One</option>

	<option value='Dark'>Dark Roast</option>

	<option value='Medium'>Medium Roast</option>

	<option value='Mild'>Mild Roast</option>

	<option value='Med-Dark'>Medium-dark Roast</option>

</select>

<span id='roastError' style='color:red'></span>

//Javascript validation code for the coffee drop-down list

if (roast === 0){

	document.getElementById("roastError").innerHTML = "You must select a roast.";

	isValid = false;

}

else{

	document.getElementById("roastError").innerHTML = "";