Sachin Prasad
Sachin Prasad

Reputation: 5411

Exit from a javascript function

I saw many places similar question but couldn't fix it.

Here's my function:

function validate_form(){
     $('#form_data input[type="text"]').each(function(){
            value = $(this).val().trim();
            if(value != '' && value != null && value != 0 ){
                   return true;
            }
     });
     return false;      
}

Its not exiting on return true;. I have also tried e.preventDefault() but no use.

Upvotes: 2

Views: 8047

Answers (3)

HMR
HMR

Reputation: 39320

function validate_form(){
     $texts=$('#form_data input[type="text"]'); //cache the object
     var len = $texts.length;
     var validItems=0;
     $texts.each(function(){
            value = $(this).val().trim();
            if(value === ''){ // value of a text input cannot be null
                              // or zero unless you've changed in with JS
                   return false;
            }
            validItems++;
     });
     return len===validItems;      
}

The function doesn't exactly show what item is invalid, just returns false if any of the items is invalid.

Upvotes: 1

Quentin
Quentin

Reputation: 944438

return will return from the function it is in. In your code, that is the anonymous function you pass to each. See the documentation for each:

You can stop the loop from within the callback function by returning false.

You are returning true, not false so you aren't stopping the loop. Change true to false on line 5 of the function.

Upvotes: 3

Ja͢ck
Ja͢ck

Reputation: 173662

You have to let the .each() finish before you return from the main function body. You can keep a counter of valid entries you have come across and let the return value depend on that:

function validate_form()
{
    var items = $('#form_data input[type="text"]'),
    count = items.length,
    valid = 0;

    items.each(function() {
        value = $(this).val().trim();
        if (value != '' && value != null && value != 0 ) {
            ++valid;
        }
    });

    return valid !== count;
}

Btw, I've changed the return value to false if there's at least one invalid entry; assuming you're using this as onsubmit="return validate_form()".

Upvotes: 0

Related Questions