4
$(document).ready(function() {

    $('#commentForm').submit(function(){

        return $('input[type=text], textarea').each(function(index){

            if($(this).attr('value') == ""){
                alert(msgHash[$(this).attr('id')]);
                return false;

            }else{

                if(!$(this).attr('value').match(validateHash[$(this).attr('id')])){
                    //Do nothing
                    alert(msgOnError[$(this).attr('id')]);
                    return false;
                }
            }
        });

        return true;
    });
});

Here msgOnError, msgHash and msgHash are map that I use to get messages for each text box with particular ID Unfortunately each method does not return false to cancel submission of the form. What am I doing wrong ?? I am new to jQuery, Thanks

0

1 Answer 1

13

Yes, that's exactly how each works. Since it's actually a loop that calls your anonymous function in each iteration, exiting those functions, will not exit the calling function as well. Returning true and false here, is actually corresponding to the continue and break of the for loop, repsectively.

You're gonna need to set a boolean flag, then return false (break), and then return the value of your boolean flag after the each

Sign up to request clarification or add additional context in comments.

2 Comments

That' s true David. I got it working by simply setting a boolean variable in the $('input[type=text], textarea').each method and also removed return keyword. Later inside the $('#commentForm') I checked the boolean and decide whether form should be submitted. Works well. Thanks again David..
i'm glad you got things working. if you're happy with a repsonse, you can tick the accept button for that answer, to mark it as the accepted answer. this shows other users know that the question has been resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.