Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery each method does not return value

$(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

like image 711
nash Avatar asked Dec 13 '22 01:12

nash


1 Answers

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

like image 75
David Hedlund Avatar answered Jan 18 '23 23:01

David Hedlund