Sam San
Sam San

Reputation: 6903

Wait for the return of the loop on form submit

I have the code below, the form is needed to be validated before it can submit the form. But the problem is, the form continues to submit without validating.

<form action='#' method='post' onsubmit='return validate();'>

function validate()
{
    $('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
    {       
        $(this).removeClass('redBox');
        var rq = $(this).attr('requiredz');

        if(rq != undefined)
        {
            if($(this).val().trim() == '')
            {
                $(this).addClass('redBox');
                $("#errorMsg").html('Red boxes cannont be left empty!');
                return false;
            }               
        }       
    });
}); 

How to handle the return of a loop? Dont submit the form once encountered return false on the loop.

Upvotes: 0

Views: 136

Answers (3)

Ram
Ram

Reputation: 144689

Each function has it's own returned value, the default returned value is an undefined value. You should check the length of the invalid elements after the each loop and return a proper value, since you are using jQuery I'd suggest:

$('form').on('submit', function (event) 
{
    var $invalid = $(this)
                    .find(':input:not(:submit,:hidden), select, textarea')
                    .removeClass('redBox')
                    .addClass(function () {
                       return this.getAttribute('requiredz') 
                              && $.trim(this.value) === ''
                              ? 'redBox' 
                              : null;
                    }).filter('.redBox');

    if ($invalid.length) 
    {
        $("#errorMsg").html('Red boxes cannont be left empty!');
        return false;
    }

});

Upvotes: 0

doubleui
doubleui

Reputation: 556

Do not use return.

$('#my-form').on('submit', function(event){
    if (validate() === false) {
        event.preventDefault(); // like return false;
    }
});

For more information see jQuery submit docs.

Upvotes: 0

Jonathan Crowe
Jonathan Crowe

Reputation: 5803

try this:

function validate()
{
    var passes = true;
    $('form').find(':input:not(:submit,:hidden), select, textarea').each(function(e)
    {       
        $(this).removeClass('redBox');
        var rq = $(this).attr('requiredz');

        if(rq != undefined)
        {
            if($(this).val().trim() == '')
            {
                $(this).addClass('redBox');
                $("#errorMsg").html('Red boxes cannont be left empty!');
                passes = false;
            }               
        }       
    });

    return passes;
}); 

Upvotes: 2

Related Questions