Prevent form submission if validation fails after iterating over each element of the form using jquery.each () function

I have the following code in which I try to iterate over html text input elements, do some validation, and prevent the form from submitting if the validation fails:

$("#the_form").submit(function(){
                $(":text", this).each(function(){                    
                    if($(this).val().length != 0)
                    {                            
                        var str = $(this).val();
                        str = $.trim($(this).val());
                        $(this).val(str);
                        if($(this).val().length < 4)
                        {
                            alert("You should enter at least 4 characters");
                            $(this).focus();
                            return false;
                        }
                    }                 
                }) // end of each() function
                return true;            
            })

If I remove the .each () function and make each element separately (which is obviously not a very good approach), I get the desired results. However, if I use the code as it is, the form continues to be submitted, even if the user has not entered four characters in the sheets. Any ideas on what I might be doing wrong here? Any help would be greatly appreciated. Thanks in advance.

+5
source share
2

return false; $.each() ( ), submit ( ). :

$("#the_form").submit(function(){
    var isValid = true;
    $(":text", this).each(function(){                    
        if($(this).val().length != 0)
        {                            
            var str = $(this).val();
            str = $.trim($(this).val());
            $(this).val(str);
            if($(this).val().length < 4)
            {
                alert("You should enter at least 4 characters");
                $(this).focus();
                isValid = false;
                return false;
            }
        }                 
    }) // end of each() function
    return isValid;
})
+6

... , . , . false : " , . , - , , , , - ". " , ".

$("#the_form").submit(function(e) {
  // LOGIC
  $(this).find(":text").each(function() {
      // OH NOES! We detected the form cannot be submitted.
      e.preventDefault();
      // More logic? maybe a shortcut exit.?
  });
});

note e.preventDefault() href, , (, e.preventDefault() checkbox.change). . http://api.jquery.com/event.preventDefault/

edit: , , . . , jquery, , , .

+1

All Articles