Event Listener on Submit Button - Javascript

I have a submit button that has an event listener of click… when the form is filled out (correctly) it should run an animation (already have made). But when the form is not filled out correctly it is still running the animation. Is there an event listener that works like a submit button, sees whether the form is valid?

const button = document.querySelector(".contact-btn");
const submit = document.querySelector(".submit");

function toggleClass() {

function addClass() {
  button.disabled = true;

button.addEventListener("click", toggleClass);

button.addEventListener("transitionend", toggleClass);
button.addEventListener("transitionend", addClass);

        <form class="contact-page__form" autocomplete="off" onsubmit="return false">
          <fieldset class="contact-page__form-wrapper">
            <div class="contact-page__input-wrapper">
              <label class="heading-contact-sub-lev p text-label">What do you call yourself?
                <input class="input-field text" type="text" name="name" required />
            <div class="contact-page__input-wrapper">
              <label class="heading-contact-sub-lev p email-label" >How should I contact you?
                <input class="input-field email" type="email" name="email" required />
            <div class="contact-page__input-wrapper">
              <label class="heading-contact-sub-lev p textarea-label"> Message:
                <textarea class="input-field textarea" type="text" name="message" spellcheck="false" required></textarea>
            <button class="contact-btn" type="submit">
                <span class="submit">send</span>
                <span class="loading"><i class="fa fa-refresh"></i></span>
                <span class="check"><i class="fa fa-check"></i></span>

I do not know what your formvalidate looks like, but make sure you prevent the default submitting of the form until your validation is complete.

Sorry, formvalidate was something I was trying out previously… I am not sure how to validate the form using the click event listener. It should be reverted the original code.

function validationFunction() {
  // Make sure to prevent the default action of when the button is clicked.  The default action is to submit the form.  Otherwise, the form gets submitted without validating it.
  // This function show iterate through each input element and check the value is "valid"
  // If they are all valid, then you would call toggleClass and submit the form (if you are actually submitting to another page).

button.addEventListener("click", validationFunction);
1 Like