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      Overall Rating   

Comment on this Code

Your Name
Comment

Recent Comments

"Your site- seandempsey.com is excellent resource, tnks, admin.
Good luck.
" - Posted by freeringtonessamsungThexUphocuche on Tuesday Jul 29th, 2008 at 7:06am

"The seandempsey.com is excellent site, thanks, owner." - Posted by ringtonesThexUphocuche on Wednesday Jul 30th, 2008 at 2:39am

"The seandempsey.com is cool site.
Thanks, admin.
" - Posted by virustestdownloadFub on Saturday Aug 2nd, 2008 at 11:54am

"Amazine site
Thanks, webmaster.
" - Posted by find best on-line savings accounts on Monday Aug 25th, 2008 at 12:41pm