Raphaël
Raphaël

Reputation: 1141

Jquery + form : no validation if val is null

My form is composed of chained select. When I arrive at last, I submit it, if and only if all the select are filled.

Here is my function.

$("#form_maps select").each(function(index, el){

                    var val = $(el).val();
                    if(val === null) 
                    {
                        alert('error message');
                        return false;
                    }
                    else 
                    {
                        $('#form_maps').submit();
                    }
                });

When I do my testing, an error is generated (the alert), but after a few seconds (I would say 2 or 3), the form is still submitted.

here is my html form

<form id="form_maps" method="post" style="height: 100px;">


    <select name="select_0" id="select_0">


                                    <option value="c_5" class="c_4">Excavateur</option>


                                    <option value="c_11" class="c_4">Compaction</option>

    </select>


    <select name="select_1" id="select_1">


                                    <option value="c_6" class="c_5">série 100</option>

                                    <option value="c_9" class="c_5">série 200</option>

    </select>


    <select name="select_2" id="select_2">



                                    <option value="c_7" class="c_6">above</option>

                                    <option value="c_10" class="c_6">thru</option>

    </select>


    <select name="select_3" id="select_3">


                                    <option value="c_8" class="c_7">système hydraulique</option>

                                    <option value="c_12" class="c_7">système électrique</option>

    </select>



</form>

What is my problem please? Thank you for your assistance to come.

Upvotes: 0

Views: 435

Answers (2)

tehshin
tehshin

Reputation: 866

I guess your form is submitted because one of the your selects has a valid value and the return false isn't stopping the loop. If you want to prevent to submit to form unless all selects do have a valid value, then I would suggest to use a boolean that will be set to false if one of the selects is invalid.

Something like this:

var canSubmit = true;
$("#form_maps select").each(function(index, el){
    var val = $(el).val();

    if(val === null) 
    {
        alert('error message');
        canSubmit = false;
    }
});

if(canSubmit) {
    $('#form_maps').submit();
}

Upvotes: 2

GuyFromOverThere
GuyFromOverThere

Reputation: 471

There is a triple is so that might be something to begin with...

Upvotes: 0

Related Questions