skwidbreth
skwidbreth

Reputation: 8454

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?

Upvotes: 1

Views: 1891

Answers (2)

rayees
rayees

Reputation: 137

Validate your form fields using JavaScript before the form is submitted and alert the user if there is an empty field or any incorrect information. Find a tutorial on form validation using javascript here, http://www.web-tutor99.com/complete-form-validation-using-javascript.html

Upvotes: 0

ratherblue
ratherblue

Reputation: 2108

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

Upvotes: 1

Related Questions