Search code examples
javascripthtmlformsbuttonrequired

How can I make a button go to the next page only if all form fields are not empty


I have a button that submits a form, but I also want it to link to another page. I only want it to link to the next page if all of the fields in the form are filled in (all fields are required). I'm thinking this will involve JavaScript, which is fine, but I'd like to avoid jQuery. Thanks.


Solution

  • The way to usually do it, is combine normal form submission with POST-Redirect-GET (the server accepts the form submission, then redirects the page).

    With normal form submission, all you need to do is mark the fields as required like so:

    <form method="post" action="/what/ever">
      <label>Name: <input required></label>
      <label>Email: <input type="email" required></label>
    
      <input type="submit" value="Send">
    </form>
    

    Example

    After the form submission is successful, redirect the page from the server-side to the next page (or to an error page, in case something went wrong).