javascripthtmlbuttononclickonsubmit

How to make work on submit function in Javascript?


Ayo,

I'm a bit struggling with functions in JS. The idea is that after the user clicks submit button, it checks if all the required fields have been filled out and if yes, it will trigger the loading animation. The loading animation is supposed to be a status indicator in the meanwhile of sending the form and redirection to the success page.

I tried to use the onsubmit function in the form HTML tag but that does not work. The important thing is that it will happen one if the required fields are filled out.

Thanks

JS

const submit_btn = document.querySelector('.submit-btn')

function loading() {
  this.innerHTML = "<div class='loader'></div>"
}

HTML

<form
  onsubmit="loading()" 
  action="https://formsubmit.co/2007080c2cf8bd2ebb68506e7aa98c5f"
  method="POST"
  enctype="multipart/form-data"
>

I tried to use the onsubmit function in the form HTML tag but that does not work.


Solution

  • In regards to validation:

    You can use the Constrained Validation API (see MDN) to check if all fields have been filled. Usually you want to use it after the user has submitted the <form> but before the form is sent to the server.

    This is achievable by using it inside an event handler that is called on submitting the form.

    In regards to event handling:

    To implement the mechanism described above, what you want to do is adding an event listener to the submit event of the form via .addEventListener() instead of the onsubmit attribute. This way you'll receive an event object as argument of the event handler function with which you can prevent the form submission.

    Example:

    const myForm = document.querySelector('form'); // or '#myform', etc...
    
    // define the event handler function
    function onFormSubmission(event) {
      const fields = Array.from(event.target.elements);
      const allValid = fields.every(field => field.reportValidity()); 
      if (!allValid) {
        event.preventDefault(); // stop form submission
        return;
      }
      event.target.innerHTML = '<div class="loading"></div>';
    }
    
    // add an event listener that fires on submission
    myForm.addEventListener('submit', onFormSubmission);
    <form id="myform" action="path/to/backend/script.php" method="POST" enctype="multipart/formdata" novalidate>
      <input type="text" name="foo" placeholder="I am required!" required>
      <hr>
      <button type="submit">Submit form</button>
    </form>

    EDIT

    Sorry, I missed to add the part that displays the loading information/element. Added (although you won't really see it because if all required fields are filled, the form will be submitted which results in a page refresh. You'd need something like XHR or similiar but that's not the scope of the question).