Prevent multiple submit via jQuery

2

I'm doing a form with validations from abide (Foundation 6) and I'm not able to prevent multiple submit's.

The following happens: When the Submit button on the form is clicked the following function takes effect.

$('#form-principal').submit(function(e) {
  e.preventDefault();
  // sem o formvalid.zf.abide do foundation, o submit acontece com campos inválidos
  $(this).on('formvalid.zf.abide', function () {
        alert('Submitou');
  });
});
The problem is this: When the submit button is clicked, Abide complains of the invalid field, so far so good, the user goes and corrects the field to abide validate correctly and clicks on Submit again, and then the function above "submited" 2x in a single click. And so on, for example: if you click 3x on submit Abide does not validate the 3x, in the 4th time if everything is right, the submit will be done 4x in a single click.

Any idea to prevent these various submit's?

HTML:

<form id="form-principal" method="post">
  <label>Teste
    <input type="text" name="teste" required>
  </label>
  <button>
    Vai filhão
  </button>
</form>

<script>
  // inicia o Foundation
  $(document).ready(function() {
    $(document).foundation();
  });
</script>
    
asked by anonymous 08.02.2017 / 14:12

2 answers

2

The problem is that with every submit of your #form-principal you add a new event listener in formvalid.zf.abide . Then it will respond to N times you have already submitted #form-principal .

If you really need to add the event to formvalid.zf.abide only when submitting #form-principal , remove the previous event and add again:

$('#form-principal').submit(function(e) {
  e.preventDefault();

  $(this).off('formvalid.zf.abide');
  $(this).on('formvalid.zf.abide', function () {
        alert('Submitou');
  });
});

I suggest you enable the submit form button within the event that validates #form-principal :

$(document)
  .on('forminvalid.zf.abide', function () {
    $('#form-principal input[type=submit]').prop('disabled', true);
  })
  .on('formvalid.zf.abide', function () {
    $('#form-principal input[type=submit]').prop('disabled', false);
  });
$('#form-principal').submit(function(e) {
  e.preventDefault();
});
    
08.02.2017 / 14:35
1

I would disable the button after the user clicked

// JavaScript

document.getElementById ("button"). disabled = true;

Or in Jquery

$ ("button") .pprop ("disabled", true);

    
08.02.2017 / 14:25