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

后端 未结 2 1594
温柔的废话
温柔的废话 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.

提交回复
热议问题