Prevent multiple Ubmit via jQuery

Asked

Viewed 394 times

2

I’m making a form with abide validations (Foundation 6) and I’m not managing to prevent several Ubmit’s.

The following happens: When it is clicked on the Submit button of the form the following function comes into action.

$('#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 as follows: When it is clicked on the Ubmit button, Abide complains about the invalid field, so far so good, the user goes and fixes the field for the abide to validate correctly and click again on Submit, and then the above function "Ubmit" 2x in a single click. And so on, for example: if you click 3x on Submit the Abide does not validate the 3x, on the 4° once it is all right, the Submit will be done 4x in a single click.

Any idea to prevent these various Ubmit’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>

2 answers

2


The problem is that with every Ubmit of your #form-principal you add a new event manager on formvalid.zf.abide. Then he will answer the N times you’ve submitted the #form-principal.

If you really need to add the event on formvalid.zf.abide only when doing the #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 button to submit the form within the event that validates the #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();
});
  • used with $(this). off('formvalid.zf.abide'); and it worked! Thank you very much!

1

I would disable the button after the user clicked

//Javascript

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

Or in Jquery

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

  • The disabled I do at the beginning of the original program, what happens is when the form is "submited", it considers the attempts I made earlier that did not work. I mean, there are times when I click 1x on the Submit button and jQuery sends Submit 3x

Browser other questions tagged

You are not signed in. Login or sign up in order to post.