validateAllSelected Javascript Function

Back to home page | View javascript file | Comment on this code

This function returns true if all the dropdown boxes on the page are selected. It is convenient for validation purposes when the user is required to fill out all options.

For this script to work correctly, you must set the value for the options that are not valid (eg "--Please Select--) to "-1".

Example




    <form name="form" onSubmit="validateAllSelected();">
    <select name="state">
        <option value="-1">Please Select a State
        <option value="VT">Vermont
        <option value="NH">New Hampshire
        <option value="CA">California
    </select>

    <select name="city">
        <option value="-1">Please Select a City
        <option value="Burlington">Burlington
        <option value="Dover">Dover
        <option value="Portsmouth">Portsmouth
    </select>
    <select name="fish">
        <option value="-1">Please Select a City
        <option value="Goldfish">Goldfish
        <option value="Rockbass">Rockbass
        <option value="Sunfish">Sunfish
    </select>

    </form>
    

And here is the javascript function to make it work.

<script>
function validateAllSelected(){
    var unSelected_ratings = 0;
    var dropdown_value;
    var the_form = document.getElementById("form");

    var dropdowns = the_form.getElementsByTagName("select");

    for (var i = 0; i < dropdowns.length; i++) {
        dropdown_value = dropdowns[i].options[dropdowns[i].selectedIndex].value;
        if (dropdown_value == -1){
            unSelected_ratings++;
        }
    }

    if (unSelected_ratings == 0){
        return true;
    }
    else{
        return false;
    }
}
</script>

Back to home page | View Javascript file | Download full example



Your Rating