Question

What I'm trying to accomplish is when a user tries to submit the form with errors and the error messages are added/page reloads I need the page to automatically scroll down to the bottom of the page to the contact form location.

I currently have the form within my footer.php and I'm including it in on each page like this: <?php include('includes/footer.php') ?>

here is my html for the form:

<form method="post" action="#">
  <input name="name" placeholder="Name*" type="text" value="<?php echo htmlspecialchars($name);?>">
     <span class="error"><?php echo $nameErr;?></span>

  <input name="email" placeholder="Email*" type="email" value="<?php echo htmlspecialchars($email);?>">
    <span class="error"><?php echo $emailErr;?></span>

  <input name="phone" placeholder="Phone #" type="tel" />

  <textarea name="message" placeholder="Message*"><?php echo $message;?></textarea>
    <span class="error"><?php echo $messageErr;?></span>

  <input id="submit" type="submit" name="submit" value="Send" />
</form>


EDIT - Based on the answer below this is what fixed my problem...

<form method="post" action="#footer">
  //everything here
</form>
Was it helpful?

Solution

While redirect to the page with error msg, add #id_of_form_or_div in your url.

Add id to your form or div which containing the form. If you add their id in url, then page will move to that particular section.

For example, You have id for footer as footer. Then you url will be www.domain.com/index.php#footer

OTHER TIPS

You can also print a javascript variable to know if there are errors, then with javascript scroll to the form.

something like:

var erros = "<?php echo $errors ?>";

<script>
    if (errors) {
        document.getElementById("form_id").scrollIntoView();
    }
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top