Home > database >  Onclick Function when input field requirements are met
Onclick Function when input field requirements are met

Time:03-31

I want the submit button's to call the function only if the input fields meet the requirements set. Is there an easier way to do it than making an if statement for each input element?

<div >
            <form>
                <input id="inputname" type="text" name="name" required placeholder="Your Name">
                <input id="email" placeholder="Your E-mail" type="email" name="email" required>
                <input id="phone" type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" placeholder="123-456-7890" required>
                <textarea type="text" rows="4" placeholder="Add comments(optional)" id="comments"></textarea>
                <button type="submit" onclick="submitted()"> Reserve a Table</button>
            </form>
</div>
    

<script>
const container = document.querySelector('.container');
function submitted() {
        container.innerHTML = `<i ></i><br>
        Thank you, the form has been submitted!`
  }
</script>
   

CodePudding user response:

Yes. See this tutorial for more details on form validation.

In particular, under the header Using built-in form validation:

When an element is invalid, the following things are true:
...
If the user tries to send the data, the browser will block the form and display an error message.

See also the note under the constraint validation process to learn more about when this happens.

The originally posted sample is shown this Fiddle but lacked a dot at the start of the container selector.

As a solution here, you can move the function call to the onsubmit handler of the form, instead of the click handler of the submit button. That fiddle is here and includes just the following changed tags: <form onsubmit="submitted()"> and <button type="submit">.

  • Related