if (document.getElementById('Roast').selectedIndex == -1){
document.getElementById("roastError").innerHTML = "You must select a roast.";
}
else{
document.getElementById("roastError").innerHTML = "";
}
Validating Drop-Down Lists
Started by Blue Indian, Sep 16 2010 12:32 PM
2 replies to this topic
#1
Posted 16 September 2010 - 12:32 PM
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:
|
|
|
#2
Posted 16 September 2010 - 11:58 PM
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.
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
Posted 17 September 2010 - 04:23 AM
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:
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 = "";


Sign In
Create Account


Back to top









