prevent form submission if validation failed after iterating over each form element with jquery's .each() function

后端 未结 2 1617
温柔的废话
温柔的废话 2021-01-13 11:49

I have the following code in which I\'m trying to iterated over html text input elements, do some validation and prevent the form submission if the validation fails:

2条回答
  •  盖世英雄少女心
    2021-01-13 12:17

    Your return false; is from within the callback function for $.each() (which makes it break at that iteration) and not from the submit handler (which would stop the form submission). This should do the trick:

    $("#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;
    })
    

提交回复
热议问题