How to stop double form submit in HTML/jQuery?
<p>I have a form in my HTML page, containing a label, an input field and a submit button.  Here is an example:</p>

<pre><code>&lt;form id="myForm" action="#"&gt;
&lt;label for="myField"&gt;My field&lt;/label&gt;
&lt;input type="text" id="myField" name="myField" class="required"&gt;
&lt;input type="submit" value="Send" /&gt;
&lt;/form&gt;
</code></pre>

<p>In my javascript code, I'm using jQuery to bind an event handler to the submit event.
This event handler overrides the default submit action.  It validates the form, performs an animation and then submits the field values to the server using an ajax call.  Here is an example:</p>

<pre><code>$("#myForm").bind("submit", function() {
  var valid = $("#myForm").validate().form();
  if (valid) {
    var val = $("#myField").val();
    $("#myForm").animate( /* blah */, function() {
      $.ajax({
        // ajax call here...
      });
    });
  }
  return false; // cancel default submit action
});
</code></pre>

<p>Note, that this is a simplified example, my real code is more complex; I also have multiple forms with different behaviours.</p>

<p>Now, I'm looking for an elegant solution to avoid re-entry: currently, the user can hit the return key multiple times, which will result in my event handler being called multiple times, and thus multiple animations and ajax requests.  I can't simply unbind/rebind inside the handler because the handler is overriding the default submit behaviour.  Also the handler itself adds callbacks to other functions: animate() and ajax().</p>

<p>The only solution I can think of is to add a boolean semaphore, that I set to true/false as in the following example :</p>

<pre><code>var myFormSubmitExecuting = false;
$("#myForm").bind("submit", function() {
  if (myFormSubmitExecuting) return;
  myFormSubmitExecuting = true;
  var valid = $("#myForm").validate().form();
  if (valid) {
    var val = $("#myField").val();
    $("#myForm").animate( /* blah */, function() {
      $.ajax({
        // ajax call here...
        // when done :
        myFormSubmitExecuting = false;
      });
    });
  } else {
    myFormSubmitExecuting = false;
  }
  return false; // cancel default submit action
});
</code></pre>

<p>I would prefer a generic solution that I can write once and apply to all my forms.  Any suggestions? </p>
