简体   繁体   English

表单验证失败后向下滚动到表单

[英]Scroll down to form after form validation failure

I have a php contact form that when submitted validates the fields but this process reloads the page and the form is not at the top of the page so I want it to automatically scroll to the bottom of the page where the form is when validation fails so the user can see the errors.我有一个 php 联系表单,提交时会验证字段,但此过程会重新加载页面并且表单不在页面顶部,所以我希望它自动滚动到验证失败时表单所在的页面底部所以用户可以看到错误。 It seems javascript is the only way to do this so I tried echo'ing a script along with the error message but it doesn't work.似乎 javascript 是执行此操作的唯一方法,因此我尝试回显脚本以及错误消息,但它不起作用。 There are no errors in the browser console, just doesn't scroll.浏览器控制台中没有错误,只是不滚动。

I took the parsed HTML from the View Source after the new page loads and put it into jsFiddle here .我在新页面加载后从 View Source 中取出解析后的 HTML 并将其放入jsFiddle here You can see that it scrolls properly in the fiddle but the real site doesn't.您可以看到它在小提琴中正确滚动,但真实站点没有。

EDIT:编辑:
I also tried adding the loading of the jquery library to immediately before the scroll script and it still didn't scroll even though I confirmed the library is loading first.我还尝试将 jquery 库的加载添加到滚动脚本之前,即使我确认库首先加载它仍然没有滚动。 I'm at a loss.我不知所措。

This is a snippet of the php:这是 php 的片段:

<?php
// define variables and set to empty values
$nameErr = $fromErr = $phoneErr = $verif_boxErr = $recaptchaErr = "";
$name    = $from = $phone = $message = $verif_box = "";
$recaptcha = NULL;
$errors  = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if form has been submitted
    if (empty($_POST["name"])) {
        $nameErr = " * Name is missing";
        $errors  = 1;
        echo '<style type="text/css"> input#name {border: 1px solid #F00; 
        box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>
        <script type="text/javascript">
function scrollSmoothToBottom(){ 
$(scrollingElement).animate({scrollTop:document.body.scrollHeight},500)
}scrollingElement=document.scrollingElement||document.body,
window.onload=scrollSmoothToBottom;</script>';
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
            $nameErr = "Only letters and white space allowed";
            $errors  = 1;
            echo '<style type="text/css"> input#name {border: 1px solid #F00; box-shadow: 0px 0px 5pt .1pt #F00 inset;}</style>';
        }
    }

if ($errors == 0) { // all fields successfullty validated. 
        $message = "Message: " . "\n" . $message;
        $message = "Name: " . $name . "\n\n" . $message;
        $message = "Email: " . $from . "\n" . $message;
        mail("website@avayoupaint.com", 'Contact Form: ' . $name, $message = "Sender IP Address: " . $_SERVER['REMOTE_ADDR'] . "\n\n" . $message, "From: website-html@avayoupaint.com");            
        setcookie('tntcon', '');    // delete the cookie so it cannot sent again by refreshing this page
        header('Location: success.php');    // redirect to success page
        exit();
}


}
?>
<html>
<head></head>
<body>
<article id="contactForm">                        
    <span class="error">* All fields are required</span>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" name="form1" id="form1">
    <span class="contactTitles">Name:</span>
    <input name="name" type="text" id="name" value="<?php echo $name;?>"/><span class="error"><?php echo $nameErr;?></span>
    </form> 
</article>
</body>
</html>

Your script to get the scrollingElement variable runs immediately when the page loads, before all the HTML is ready and loaded into the page.在页面加载时,在所有 HTML 准备好并加载到页面之前,您获取scrollingElement变量的脚本会立即运行。 You need to wait until all the content is loaded, otherwise the script will not find the document.body object to attach the scroll animation to.您需要等到所有内容加载完毕,否则脚本将找不到document.body object 来附加卷轴 animation。 This is especially a problem because the script is positioned before the HTML document.这尤其是一个问题,因为该脚本位于 HTML 文档之前。 Browsers execute script as soon as they receive it, they don't wait until the whole document is loaded.浏览器在收到脚本后立即执行,他们不会等到整个文档加载完毕。

jQuery provides the document.ready event handler for you to wrap your Javascript in, so that the main script waits for the page to be in the state where all the HTML has loaded (there's also a native JS way to do the same thing, but since you're using jQuery we'll do it this way). jQuery 为您提供了document.ready事件处理程序来包装您的 Javascript,以便主脚本等待页面位于 state 中,其中所有 HTML 已加载(还有一种本机 JS 方法可以做同样的事情,但是因为您使用的是 jQuery,所以我们会这样做)。 You actually already have an example of this in your current site, right down near the bottom.实际上,您当前的站点中已经有一个这样的示例,就在底部附近。

It also makes more sense for the scrollingElement to be inside the function - it doesn't have much purpose being a global, as it's only used within that one function.将 scrollingElement 放在 function 内部也更有意义——它作为一个全局元素没有太大意义,因为它只在 function 中使用。

<script type="text/javascript">
  $(document).ready(function() {

  function scrollSmoothToBottom() { 
    var scrollingElement = document.scrollingElement || document.body;
    $(scrollingElement).animate({ scrollTop:document.body.scrollHeight }, 500);
  }
    scrollSmoothToBottom();
  });
</script>

Note that this version requires jQuery to be loaded before this script block runs.请注意,在此脚本块运行之前,此版本需要加载 jQuery。 It would make sense to output the script block somewhere in the <head> section of the page, just below a <script block which loads jQuery. output 脚本块位于页面的<head>部分的某处,就在加载 jQuery 的<script块下方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM