Search code examples
htmlformsvalidationrequired

HTML form validation - check 'required' attribute before proceeding


I have an html form with required text fields, something like this -

<form>
  <input type="text" class="text_input" required>
  <input type="text" class="text_input" required>
  <div id="submit_div">
      <input type="submit id="submit">
  </div>
</form>

In order to prevent accidental repeat submissions (such as when someone clicks submit twice, either accidentally our impatiently), I have added the following script which hides the original submit button and replaces it with an element that is basically identical in appearance but is non-functional

$("#submit")click(function() {
    $("#submit").hide();
    $("#submit_div").append('<div id="submitting" class="buttonText animated flash">Submitting...</br><div class="againStop" id="stop">Please wait</div></div>');
});

The problem that I am bumping in to is that clicking the submit button before the required field is filled out triggers this script, removing the button from the page and preventing the user from submitting the form after they fill in the required field.

What I need is something that tells the hide and append methods in my function to trigger only if all required fields have been filled. How can I access the required property of all required fields and check that they are returning true before proceeding so that the methods only trigger if all required fields are filled out?


Solution

  • Add an event listener to the onsubmit event for your form, and add return: false if the checks fail.