Need Help with Drop-down List Validation

I want to carry out form validation for drop down lists. My website has 10 drop down lists. I want an alert message to be displayed whenever the user selects a blank field from a drop down list. One of the sample drop down list runs as follows:


<strong>Groom's Current Profession</strong>
    <form name="profession">
        <select name="groomprofession" onchange="formValues('profession', 'groomprofession')">
            <option value="c1"></option>
            <option value="c2">Doctor</option>
            <option value="c3">Engineer</option>
            <option value="c4">Lawyer</option>
            <option value="c5">CA</option>
            <option value="c6">Family Business</option>
            <option value="c7">Teacher</option>
            <option value="c8">Journalist</option>
            <option value="c9">Business Analyst</option>
        </select>
    </form>

How can I include a function that displays an alert message whenever a user selects a blank option from the drop down list? Thanks!

Will the blank option always be the first one in the list? If so, the script then doesn’t need to know anything about it being blank, and can just check to see if it is the first one that is selected.

Thanks for your reply Paul. Yes, the blank option is the first in the drop down list. How can I go about checking it? (Something like checking if the value of the first index is blank or not?)

Is the following piece of code correct? [just for checking one drop down list as an example]


function ValidateForm( )
{
    valid = true;
    var si_2 = document.Profession.Groomprofession.selectedIndex;
    if (document.CheckForm.Profession.Groomprofession.options[si_2].text == "" )
    {
        alert ( "Please select Groom's profession" );
        valid = false;
    }

    return valid;
}

And then the following piece of code in the body tags?


<form method="post" name="CheckForm" onsubmit="return ValidateForm();">

Basically I am facing problem in checking if the user selects the first option from the drop down list or not. Thanks a lot for looking into the problem!

Refining on the above code, you could do something like this:


var select = document.Profession.Groomprofession; 
if (select.selectedIndex === 0) {

Thanks for the reply, Paul. I implemented the code but it is not working. May be because it does not know what ‘CheckForm’ is? Do I need to include that in the function ValidateForm as well? And if not, how would the one line code in the <body> tag look like? Thanks!

The name that you have given the form is virtually useless in normal terms.

It’s like giving a name to an anchor element:

<a name="content"></a>

That’s a technique that was in place before unique identifiers existed.

These days we would instead use something like this:

<div id="content"></div>

Getting back to your code, the form should use a unique identifier on the form tag instead.


<form method="post" id="CheckForm">

That way, you can put a script at the end of the body which retrieves a reference to the form, and attaches a function to the onsubmit event.


var form = document.getElementById('CheckForm');
form.onsubmit = ValidateForm;

The benefit of doing it that way, is that within the ValidateForm function, the this keyword can now be used to refer to the element that triggered the event.


function ValidateForm() {
    var form = this;
    ...
}

which you can then leverage in different ways, for example:


var select = form.elements.Groomprofession; 
if (select.selectedIndex === 0) {
    ...
}

Thanks for the detailed reply, Paul. I am still facing problems in getting it to work. Sorry for asking all the stupid questions, but I am a bit new to JS. I am pasting my entire code below (with the code for the form validation in the bold that I added just now):


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample title..</title>
<script type = "text/javascript">
//<![CDATA[
    var opts = [];
    var age, caste, profession, bachelor, master, doc, country, color, height, marriage, father;

    function formValues(form, ele) {
        var form = document.forms[form].elements[ele],
            val  = form.value, index = form.selectedIndex;

        if (typeof opts[ele] === 'undefined') opts.push(ele);
        opts[ele] = form.options[index].text;
    }

[B]function ValidateForm( )
{
    valid = true;
    var select = document.profession.groomprofession;
    if (select.selectedIndex === 0 )
    {
        alert ( "Please select Groom's profession" );
        valid = false;
    }

    return valid;
}    [/B]

function processForm() {
        var set = [
            {form: 'age', ele: 'groomage'},
            {form: 'caste', ele: 'groomcaste'},
            {form: 'profession', ele: 'groomprofession'},
            {form: 'bachelor', ele: 'groombachelor'},
            {form: 'master', ele: 'groommaster'},
            {form: 'doc', ele: 'groomdoc'},
            {form: 'country', ele: 'groomcountry'},
            {form: 'color', ele: 'groomcolor'},
            {form: 'height', ele: 'groomheight'},
            {form: 'marriage', ele: 'groommarriage'},
            {form: 'father', ele: 'groomfather'}
        ];

        for (var i in set) {
            formValues(set[i].form, set[i].ele);
        }

        switch (opts['groomage']) {
            case '23':
                age = 1.6;
            break;

            case '24':
                age = 1.2;
            break;

            case '25':
            case '29':
            case '46-50':
                age = 1.7;
            break;

            case '26':
            case '31-35':
                age = 1.8;
            break;

            case '27':
            case '36-40':
                age = 1.9;
            break;

            case '28':
            case '41-45':
                age = 1.75;
            break;

            case '30':
            case '51+':
                age = 1.4;
            break;

            default:
                age = 1;
        }

        switch (opts['groomcaste']) {
            case 'Bania':
                caste = 1.2;
            break;

            case 'Brahmin':
            case 'Labanas':
            case 'Rajput':
            case 'Maravar':
            case 'Kayastha':
                caste = 1.6;
            break;

            case 'Dalit':
            case 'Jat':
                caste = 1.8;
            break;

            case 'Kshatriya':
            case 'Mudaliar':
                caste = 2.0;
            break;

            default:
                caste = 1;
        }

        switch (opts['groomprofession']) {
            case 'Doctor':
                profession = 1.2;
            break;

            case 'Family Business':
                profession = 1.5;
            break;

            case 'Engineer':
                profession = 1.6;
            break;

            case 'Lawyer':
                profession = 1.65;
            break;

            case 'CA':
                profession = 1.7;
            break;

            case 'Engineer + MBA':
            case 'None of the above':
                profession = 1.95;
            break;

            case 'IAS':
                profession = 2.0;
            break;

            default:
                profession = 1;
        }

        switch (opts['groombachelor']) {
            case 'BBA':
            case 'BA':
                bachelor = 1.1;
            break;

            case 'MBBS':
                bachelor = 1.2;
            break;

            case 'Diploma':
            case 'B.Com':
            case 'Certification Course':
                bachelor = 1.4;
            break;

            case 'BTech/BE/BS':
                bachelor = 1.6;
            break;

            case 'BSc':
                bachelor = 1.9;
            break;

            default:
                bachelor = 1;
        }

        switch (opts['groommaster']) {
            case 'MBA':
                master = 1.2;
            break;

            case 'MHA':
            case 'MTech':
            case 'M.Ed':
            case 'No Master degree':
                master = 1.4;
            break;

            case 'MS':
                master = 1.6;
            break;

            default:
                master = 1;
        }

        switch (opts['groomdoc']) {
            case 'Doctor of Medicine (MD)':
                doc = 1.2;
            break;

            case 'No Doctorate Degree':
                doc = 1.4;
            break;

            case 'Doctor of Philosophy (Phd)':
                doc = 1.6;
            break;

            default:
                doc = 1;
        }

        switch (opts['groomcountry']) {
            case 'USA':
            case 'Any Country less developed than India':
                country = 1.2;
            break;

            case 'India':
                country = 1.6;
            break;

            case 'Any European Country':
            case 'Australia':
            case 'Canada':
            case 'Any Country more developed than India':
                country = 1.7;
            break;

            default:
                country = 1;
        }

        switch (opts['groomcolor']) {
            case 'Pitch Black (Not visible on a moonless night)':
                color = 0.6;
            break;

            case 'Black':
                color = 1.2;
            break;

            case 'Brown':
            case 'Wheatish (Almost White. Would need some Fair n Lovely)':
                color = 1.4;
            break;

            case 'Fairy White':
                color = 1.6;
            break;

            case 'White':
                color = 1.9;
            break;

            default:
                color = 1;
        }

        switch (opts['groomheight']) {
            case '5\\'5"':
                height = 0.8;
            break;

            case '5\\'6"':
                height = 1.0;
            break;

            case '5\\'4"':
                height = 1.2;
            break;

            case '5\\'7"':
                height = 1.4;
            break;

            case '5\\'8"':
                height = 1.5;
            break;

            case '5\\'9"':
            case 'Less than 5\\'4"':
                height = 1.6;
            break;

            case '5\\'10"':
                height = 1.7;
            break;

            case '5\\'11"':
            case 'Greater than 6\\'1"':
                height = 1.8;
            break;

            case '6':
                height = 1.85;
            break;

            case '6\\'1"':
                height = 1.9;
            break;

            default: height = 1;
        }

        switch (opts['groommarriage']) {
            case 'More than 2':
                marriage = 0.2;
            break;

            case '2':
                marriage = 0.4;
            break;

            case '1':
                marriage = 1.2;
            break;

            case '0':
                marriage = 1.6;
            break;

            default:
                marriage = 1;
        }

        switch (opts['groomfather']) {
            case 'IAS':
            case 'Family Business':
                father = 1.2;
            break;

            case 'Doctor':
                father = 1.6;
            break;

            case 'Lawyer':
                father = 1.65;
            break;

            case 'Engineer':
                father = 1.7;
            break;

            case 'CA':
                father = 1.8;
            break;

            case 'Engineer + MBA':
                father = 1.9;
            break;

            default:
                father = 1;
        }
    }

    window.onload = processForm;

    function processOrder() {
        processForm();

        var total = age + caste + bachelor + master + doc + color + profession + father + marriage + height + country;
        var pageNumber = Math.floor((20 - total) / 2 + 1);

        //alert(pageNumber);
        window.open('Page ' + pageNumber + '.html');
    }
//]]>
</script>
</head>
<body>
<body bgcolor="#ADD8E6">

<script type = "text/javascript">
var form = document.getElementById('CheckForm');
form.onsubmit = ValidateForm;
</script>

<center>
    <font size="6"><strong><em>sample text 1*</em></strong></font>
</center>

<br /><br />
<br /><br />

<em>*sample text 2</em>

<center>
    <strong>Groom's Age</strong>
    <form name="age">
        <select name="groomage" onclick="formValues('age', 'groomage')">
            <option value="a1"></option>
            <option value="a2">23</option>
            <option value="a3">24</option>
            <option value="a4">25</option>
            <option value="a5">26</option>
            <option value="a6">27</option>
            <option value="a7">28</option>
            <option value="a8">29</option>
            <option value="a9">30</option>
            <option value="a10">31-35</option>
            <option value="a11">36-40</option>
            <option value="a12">41-45</option>
            <option value="a13">46-50</option>
            <option value="a14">51+</option>
        </select>
    </form>

    <strong>Groom's Caste</strong>
    <form name="caste">
        <select name="groomcaste" onchange="formValues('caste', 'groomcaste')">
            <option value="b1"></option>
            <option value="b2">Brahmin</option>
            <option value="b3">Bania</option>
            <option value="b4">Kayastha</option>
            <option value="b5">Kshatriya</option>
            <option value="b6">Dalit</option>
            <option value="b7">Maravar</option>
            <option value="b8">Mudaliar</option>
            <option value="b9">Nair</option>
            <option value="b10">Jat</option>
            <option value="b11">Labanas</option>
            <option value="b12">Rajput</option>
        </select>
    </form>

    <strong>Groom's current Profession</strong>
    <form name="profession">
[B]<form method="post" id="CheckForm">[/B]
        <select name="groomprofession" onchange="formValues('profession', 'groomprofession')">
            <option value="c1"></option>
            <option value="c2">Doctor</option>
            <option value="c3">Engineer</option>
            <option value="c4">Lawyer</option>
            <option value="c5">CA</option>
            <option value="c6">IAS</option>
            <option value="c7">Engineer + MBA</option>
            <option value="c8">Family Business</option>
            <option value="c9">None of the above</option>
        </select>
    </form>

    <strong>Groom's Degree at the Bachelor's Level</strong>
    <form name="bachelor">
        <select name="groombachelor" onchange="formValues('bachelor', 'groombachelor')">
            <option value="d1"></option>
            <option value="d2">BTech/BE/BS</option>
            <option value="d3">MBBS</option>
            <option value="d4">BA</option>
            <option value="d5">B.Com</option>
            <option value="d6">B.Ed</option>
            <option value="d7">Bsc</option>
            <option value="d8">BBA</option>
            <option value="d9">Diploma</option>
            <option value="d10">Certification Course</option>
        </select>
    </form>

    <strong>Groom's Degree at the Master's Level</strong>
    <form name="master">
        <select name="groommaster" onchange="formValues('master', 'groommaster')">
            <option value="e1"></option>
            <option value="e2">MBA</option>
            <option value="e3">MS</option>
            <option value="e4">MTech</option>
            <option value="e5">MPhil</option>
            <option value="e6">M.Ed</option>
            <option value="e7">MHA</option>
            <option value="e8">No Master degree</option>
        </select>
    </form>

    <strong>Groom's Degree at the Doctorate Level</strong>
    <form name="doc">
        <select name="groomdoc" onchange="formValues('doc', 'groomdoc')">
            <option value="f1"></option>
            <option value="f2">Doctor of Philosophy (Phd)</option>
            <option value="f3">Doctor of Medicine (MD)</option>
            <option value="f4">No Doctorate Degree</option>
        </select>
    </form>

    <strong>The Groom is working in</strong>
    <form name="country">
        <select name="groomcountry" onchange="formValues('country', 'groomcountry')">
            <option value="g1"></option>
            <option value="g2">India</option>
            <option value="g3">USA</option>
            <option value="g4">Any European Country</option>
            <option value="g5">Australia</option>
            <option value="g6">Canada</option>
            <option value="g7">Any Country more developed than India</option>
            <option value="g8">Any Country less developed than India</option>
        </select>
    </form>

    <strong>Groom's Skin Color</strong>
    <form name="color">
        <select name="groomcolor" onchange="formvalues('color', 'groomcolor')">
            <option value="h1"></option>
            <option value="h2">Fairy White</option>
            <option value="h3">White</option>
            <option value="h4">Wheatish (Almost White. Would need some Fair n Lovely)</option>
            <option value="h5">Brown</option>
            <option value="h6">Black</option>
            <option value="h7">Pitch Black (Not visible on a moonless night)</option>
        </select>
    </form>

    <strong>Groom's Height</strong>
    <form name="height">
        <select name="groomheight" onchange="formvalues('height', 'groomheight')">
            <option value="i1"></option>
            <option value="i2">Less than 5'4"</option>
            <option value="i3">5'5"</option>
            <option value="i4">5'6"</option>
            <option value="i5">5' 7"</option>
            <option value="i6">5'8"</option>
            <option value="i7">5'9"</option>
            <option value="i8">5' 10"</option>
            <option value="i9">5'11"</option>
            <option value="i10">6'</option>
            <option value="i11">6'1"</option>
            <option value="i12">Greater than 6'1"</option>
        </select>
    </form>

    <strong>Number of times the Groom has married before</strong>
    <form name="marriage">
        <select name="groommarriage" onchange="formvalues('marriage', 'groommarriage')">
            <option value="j1"></option>
            <option value="j2">0</option>
            <option value="j3">1</option>
            <option value="j4">2</option>
            <option value="j5">More than 2</option>
        </select>
    </form>

    <strong>What is Groom's father's profession</strong>
    <form name="father">
        <select name="groomfather" onchange="formvalues('father', 'groomfather')">
            <option value="k1"></option>
            <option value="k2">Engineer</option>
            <option value="k3">Doctor</option>
            <option value="k4">IAS</option>
            <option value="k5">Lawyer</option>
            <option value="k6">CA</option>
            <option value="k7">IAS</option>
            <option value="k8">Engineer + MBA</option>
            <option value="k9">Family Business</option>
            <option value="k10">None of the above</option>
        </select>
    </form>

[B]<script type = "text/javascript">
var form = document.getElementById('CheckForm');
form.onsubmit = ValidateForm;
</script>
[/B]

<input type="button" value="Calculate" onclick="processOrder()" />

 </body>
</html>

I think that you are using the form tag incorrectly. When you submit a form, only the data from the one form that’s associated with the submit button or event is sent.

In other words, only the one form tag should be used, and that should surround all of the form fields that you want to be submitted.

Thanks for the reply, Paul.

So does that mean instead of CheckForm I should just use groomprofession and delete this piece of code “<form method=“post” id=“CheckForm”>”?

It means that before you can even think of using JavaScript, you need to get your fundamental basics of the HTML right.

Use only the one form tag, and wrap that form tag around all of the form fields that you require to be submitted.

I am trying to learn the ropes. You don’t have to be so rude!

I’m just laying down the facts. JavaScript performs a lot of work with the HTML. It’s just not possible for JavaScript to perform the work you require it to do, when the HTML code is not correctly formed.

That means that before performing JavaScript work, you need to get the HTML code working correctly.

If you take umbrage at such basic fundamentals of scripting, well - I don’t know how to be any less rude than that.

what should i do if i want message rather than an alert on validation

In such a case, don’t use an alert, and update the content of an HTML element instead.