0

"return false;" for form submission is working for the rest of my code, just not this section. Any ideas why?

function checkForm() {
    $("select[name*=lic_company]").each(function() {
        if($(this).val() != '') {
            var i1 = $(this).parent("td").next("td").children("select");
            var i2 = i1.parent("td").next("td").children("input");
            var i3 = i2.parent("td").next("td").children("input");
            if(i1.val() == '') {
                i1.parent("td").addClass("formErrorTD");
                i1.addClass("formError");
                alert("You must enter a state for this license");
                return false;
            }
            if(i2.val() == '') {
                i2.parent("td").addClass("formErrorTD");
                i2.addClass("formError");
                alert("You must enter an expiration date for this license");
                return false;
            }
            if(i3.val() == '') {
                i3.parent("td").addClass("formErrorTD");
                i3.addClass("formError");
                alert("You must enter a license number for this license");
                return false;
            }
        }
    });
}

and it's being called by

$("#addAgentForm").submit(checkForm);
4

3 に答える 3

3

You are calling return false; within a closure that is an argument passed to .each. Therefore, .each is capturing the return false;. To get around this you need need to have a boolean flag that holds the state of the form:

function checkForm() {
    var okay = true;

    $("select[name*=lic_company]").each(function() {
    ...
        return okay = false;
    ...
    });

    return okay;
}

And everything will work fine.

于 2012-04-07T16:00:08.657 に答える
1

Your return false statements are inside the anonymous function passed to .each(), so only return a value from that function, not the entire call to checkForm().

于 2012-04-07T16:00:07.820 に答える
0

If I had to guess, it's because you're returning from the function passed to your each call, meaning all you're really doing is exiting your each function while your main validation function finishes without a hitch.

于 2012-04-07T16:01:04.673 に答える