-1

On my page, I would not use PHP to send emails (please, do not comment) then came to a solution with external service which is invoked by fetch. That is why I submit my form data with onclick function; and this onclick is bound to button. Practically this onclick doesn't use form features, it simply grabs form's data by its ID.

That button stays outside of the form. Needless to say that in that case, I do not benefit from typical form features like required and pattern validate.

Is there a simple way to have a button which sends data by onclick and also triggers form validation? By form validation, I mean usual internal HTML validation. Of course I could develop validation within onclick function body, but that is not what I am looking for - I'd like to use form's features instead.

1 Answers1

0

You're going to want to throw your submit button back into your form so you can take advantage of all those built-in features, and then you're going to use the submit event on your form and then take advantage of fetch, URLSearchParams, and FormData as follows:

// HTML

<form id="form">
    <!-- inputs go here... -->
    <button type="submit">Submit</button>
</form>

// JavaScript

const form = document.querySelector('form');

form.addEventListener('submit', (e) => {

    // prevents default submission so we can do our magic
    e.preventDefault();

    // build request
    const formData = new FormData(form);

    fetch('some/endpoint', {
        method: 'post',
        body: new URLSearchParams(formData),
    });

    // do something else...

});

These are all modern best practices, but they aren't great with compatibility. You might have to look at XMLHttpRequest instead of fetch and even looping through form elements instead of using FormData, but this should put you in the right direction.

sheng
  • 1,226
  • 8
  • 17
  • 1
    Thank you. It looks good, I will test it on afternoon. That way you avoid using onclick which as I see is in conflict with type='submit'. Yes, it looks very promising – Kiszuriwalilibori Mar 08 '19 at 07:33