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

后端 未结 2 1595
温柔的废话
温柔的废话 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:07

    Simple... You just prevent the default of the event if you want it to stop. Please DO NOT RETURN FALSE. Returning false from an event is like saying: "I want you to fail. Not only that I want to make sure that any event handler registered after me does not get executed, and no bubbling happens because some shit just went wrong". You want "prevent the action the browser does normally from happening".

    $("#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() will stop links from going to their href target, will prevent form submission, will even prevent a change handler from allowing the change (say e.preventDefault() on a checkbox.change event). See http://api.jquery.com/event.preventDefault/

    edit: Note that the event handler is always passed the event object as a parameter, in your code you just ignored it. Read up on event handler function. There are really nifty features that you can do with events in jquery, don't ingore them as they are quite useful at times especially when you need to get some data to the handler.

    0 讨论(0)
  • 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;
    })
    
    0 讨论(0)
提交回复
热议问题