views:

93

answers:

4

hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page

$('#loginAccount').submit(function() {
$(this).find(':input:text')
     .each(function(i) {
    if($(this).val()=="")
    {
        //alert($('label').eq(i).html())
        $('#alert3').html('Please fill all fields.');
        return false;
    }
});
})
A: 

You need to return false in the submit function, not the each function:

$('#loginAccount').submit(function() {
    var isValid = true;
    $(this).find(':input:text').each(function(i) {
        if($(this).val()=="")
        {
            isValid = false;
            //alert($('label').eq(i).html())
            $('#alert3').html('Please fill all fields.');

        }
    });
    return isValid;
});
Mark B
This will always return false.
Emil Ivanov
Ooops, you're right! Too quick on the draw...
Mark B
+5  A: 
$('#loginAccount').submit(function() {
var valid = true;
$(this).find(':input:text')
     .each(function(i) {
    if($(this).val()=="")
    {
        //alert($('label').eq(i).html())
        $('#alert3').html('Please fill all fields.');
        valid = false;
    }
});
return valid;
})

You are currently returning from the each. What you need to do is track whether it's valid and then use that value as the return from your submit.

Keith Rousseau
:)) why couldn't i think this, thank you Keith
dexamel
+4  A: 

return false; takes on a different meaning inside of a jQuery each(). It is used to break out of the each. Maybe you could set a flag that is observed after the each() to see if the validation succeeded.

patrick dw
Thank you for this small explanation. I've had the same problem a while ago, I thought it was because the target page already started loading when javascript returns true, but i was wrong.
Daan
thank you patrick
dexamel
A: 

May be you shoul use closure to return a value?

    $('#loginAccount').submit(function() {
           var result = true;    
            $(this).find(':input:text')
                 .each(function(i) {
                if($(this).val()=="")
                {
                    //alert($('label').eq(i).html())
                    $('#alert3').html('Please fill all fields.');
                    result = false;
                }
            });
            return result;
            })
Steck