Search code examples
javascripthtmlformsecmascript-6ecmascript-5

Form doesn't get submitted when there's click event on submit button


I have form where's a click event listener on the submit button. When the submit button is clicked the event click event listener on the button gets fired, but the form doesn't get submitted.

Here's my code:

<!-- HTML -->
<form action="/customer/create" method="post">
  <input type="text" name="email">
  <button type="submit" class="has-button-spinner">Create Customer</button>
</form>

<!-- JS -->
const buttons = document.querySelectorAll('.has-button-spinner');

buttons.forEach((button) => {
  button.addEventListener('click', (e) => {
    const target = e.currentTarget;

    target.classList.add('is-loading');
    target.setAttribute('disabled', true);
  });
});

Solution

  • When you disable your <button>, you prevent its action (submitting the form) from taking place.

    Instead of listening to the click event of your button, listen to the submit event of your form :

    const forms = document.querySelectorAll('form');
    
    forms.forEach((form) => {
      form.addEventListener('submit', (e) => {
        const target = form.querySelector('button.has-button-spinner');
    
        target.classList.add('is-loading');
        target.setAttribute('disabled', true);
      });
    });
    <form action="/customer/create" method="post">
      <input type="text" name="email">
      <button type="submit" class="has-button-spinner">Create Customer</button>
    </form>