简体   繁体   English

表单返回错误时如何返回页面的特定部分

[英]How to return to a certain section of a page when a form comes back with errors

I have a one page website. 我有一个一页的网站。 Each menu item scrolls you to a different part of the page. 每个菜单项会将您滚动到页面的不同部分。 I have a HTML and PHP form which reloads the page and displays an error message if the form is submitted with a required field not filled. 我有一个HTML和PHP表单,如果提交表单时未填写必填字段,则会重新加载页面并显示错误消息。 The problem is it reloads to the top of the page whereas my form is at the bottom of the page. 问题是它重新加载到页面顶部,而我的表单在页面底部。

How can I get the form to reload the page to the section where the contact form is? 如何获取表格以将页面重新加载到联系表格所在的部分? The form already does exactly that when the form is submitted successfully but not when there are errors. 当成功提交表单时,表单已经完全做到了这一点,但是在出现错误时,表单就不会这么做。

Any help would be great. 任何帮助都会很棒。 Thanks for reading. 谢谢阅读。

HTML HTML

<div id="contactBox">

            <form name="contact" id="contactForm" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <div id="formLeft">
                    <p>
                        <label for="name">Name</label>
                        <?php if ($missing && in_array('name', $missing)) { ?>
                        <div class="warningDivLeft">
                        <span class="warning">Please enter your name</span>
                        </div>                             
                        <?php } ?>
                        <input type="text" name="name" id="name" tabindex="10"
                        <?php
                        if ($errors || $missing) {
                            echo 'value="' . htmlentities($name, ENT_COMPAT, 'utf-8') . '"';
                        }
                        ?>      
                        >
                    </p>
                    <p>                           
                        <label for="company">Company Name/Website</label>
                        <input type="text" name="company" id="company" tabindex="30"
                        <?php
                        if ($errors || $missing) {
                            echo 'value="' . htmlentities($company, ENT_COMPAT, 'utf-8') . '"';
                        }
                        ?>      
                        >
                    </p>
                    <p>                           
                        <label for="email">Email</label>
                        <?php if ($missing && in_array('email', $missing)) { ?>
                        <div class="warningDivLeft">
                        <span class="warning">Please enter your email</span>
                        </div>
                        <?php } elseif (isset($errors['email'])) { ?>
                        <div class="warningDivLeft">
                        <span class="warning">Invalid email address</span>
                        </div>
                        <?php } ?>
                        <input type="email" name="email" id="email" tabindex="40"
                        <?php
                        if ($errors || $missing) {
                            echo 'value="' . htmlentities($email, ENT_COMPAT, 'utf-8') . '"';
                        }
                        ?>      
                        >
                    </p>
                    <p>                           
                        <label for="phone">Phone</label>
                        <input type="text" name="phone" id="phone" tabindex="50"
                        <?php
                        if ($errors || $missing) {
                            echo 'value="' . htmlentities($phone, ENT_COMPAT, 'utf-8') . '"';
                        }
                        ?>      
                        >
                    </p>
                    <p>                           
                        <label for="contactYou">Contact you by...</label>
                        <?php if ($missing && in_array('contactYou', $missing)) { ?>
                        <div class="warningDivLeft">
                        <span class="warning">Please select one</span>
                        </div>
                        <?php } ?>
                        <select name="contactYou" size="1" id="contactYou" tabindex="60">
                            <option value="" selected="selected">- select</option>
                            <option value="email" <?php echo ($contactYou == 'email') ? ' selected="selected"' : ''; ?>>Email</option>
                            <option value="phone" <?php echo ($contactYou == 'phone') ? ' selected="selected"' : ''; ?>>Phone</option>
                        </select>
                    </p> 
                </div>
                <div id="formRight">
                    <p>
                        <label for="interest">I am interested in...</label>
                        <?php if ($missing && in_array('interest', $missing)) { ?>
                        <div class="warningDiv">
                        <span class="warning">Please select one</span>
                        </div>
                        <?php } ?>
                        <select name="interest" size="1" id="interest" tabindex="80">
                            <option value="" selected="selected">- select</option>
                            <option value="new" <?php echo ($interest == 'new') ? ' selected="selected"' : ''; ?>>Creating a new website</option>
                            <option value="current" <?php echo ($interest == 'current') ? ' selected="selected"' : ''; ?>>Redesigning a current website</option>
                            <option value="responsive" <?php echo ($interest == 'responsive') ? ' selected="selected"' : ''; ?>>Reponsive web design</option>
                            <option value="wordpress" <?php echo ($interest == 'wordpress') ? ' selected="selected"' : ''; ?>>A WordPress website</option>
                            <option value="general" <?php echo ($interest == 'general') ? ' selected="selected"' : ''; ?>>General enquiry</option>
                        </select>
                    </p>
                    <p>
                        <label for="budget">My budget is...</label>
                        <?php if ($missing && in_array('budget', $missing)) { ?>
                        <div class="warningDiv">
                        <span class="warning">Please select one</span>
                        </div>
                        <?php } ?>
                        <select name="budget" size="1" id="budget" tabindex="90">
                            <option value="" selected="selected">- select</option>
                            <option value="100" <?php echo ($budget == '100') ? ' selected="selected"' : ''; ?>>€100 - €500</option>
                            <option value="500" <?php echo ($budget == '500') ? ' selected="selected"' : ''; ?>>€500 - €1,000</option>
                            <option value="1000" <?php echo ($budget == '1000') ? ' selected="selected"' : ''; ?>>€1,000 - €2,000</option>
                            <option value="2000" <?php echo ($budget == '2000') ? ' selected="selected"' : ''; ?>>€2,000 - €5,000</option>
                            <option value="5000" <?php echo ($budget == '5000') ? ' selected="selected"' : ''; ?>>€5,000 - €10,000</option>
                            <option value="10000" <?php echo ($budget == '10000') ? ' selected="selected"' : ''; ?>>€10,000+</option>
                        </select>
                    </p>
                    <p>
                        <label for="comments">How can I help you?</label>
                        <?php if ($missing && in_array('comments', $missing)) { ?>
                        <div class="warningDiv">
                        <span class="warning">Please leave a comment</span>
                        </div>
                        <?php } ?>
                        <textarea name="comments" id="comments" cols="45" rows="5" tabindex="100"><?php
                        if ($errors || $missing) {
                            echo htmlentities($comments, ENT_COMPAT, 'utf-8');
                        }
                        ?></textarea>
                    </p>
                </div>
                <div id="formSubmit">
                    <ul>
                        <li>
                          <input type="submit" name="submit" id="submit" value="Send Message" tabindex="70">
                        </li>
                    </ul>
                </div>
                    </form>

PHP PHP

<?php
$errors = array();
$missing = array();
if (isset($_POST['submit'])) {
    $to = 'celinehalpin@hotmail.com';
    $subject = 'Web Design';
    $expected = array('name', 'company', 'email', 'phone', 'contactYou', 'interest', 'budget', 'comments');
    $required = array('name', 'email', 'contactYou', 'interest', 'budget', 'comments');
    $headers = "From: webmaster@example.com\r\n";
    $headers .= "Content-type: text/plain; charset=utf-8";
    $authenticate = '-fcelinehalpin@hotmail.com';
    require './_includes/mail_process.php';
    if ($mailSent) {
        header('Location: ' . $_SERVER['REQUEST_URI'] . '?success=1#c');
        exit;   
    }
}
?>


<?php if (($_POST && $suspect) || ($_POST && isset($errors['mailfail']))) { ?>
        <div class="globalWarning">
        <p class="warning">Sorry your mail could not be sent</p>
        </div>
<?php } elseif ($errors || $missing) { ?>
        <div class="globalWarning">
        <p class="warning">Please fix the item(s) indicated</p>
        </div>
<?php } elseif (isset($_GET['success'])) { ?>
        <div class="globalAlert">
        <p class="warning">Thank you! Your message has been sent!</p>
        </div>
<?php } ?>

<?php
$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';

function isSuspect($val, $pattern, &$suspect) {
    if (is_array($val)) {
        foreach ($val as $item) {
            isSuspect($item, $pattern, $suspect);   
        }
    } else {
        if (preg_match($pattern, $val)) {
            $suspect = true;    
        }
    }
}

isSuspect($_POST, $pattern, $suspect);

if (!$suspect) {
    foreach ($_POST as $key => $value) {
        $temp = is_array($value) ? $value : trim($value);
        if (empty($temp) && in_array($key, $required)) {
            $missing[] = $key;
            $$key = '';
        } elseif(in_array($key, $expected)) {
            $$key = $temp;
        }
    }
}

if (!$suspect && !empty($email)) {
    $validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($validemail) {
        $headers .= "\r\nReply-to: $validemail";
    } else {
        $errors['email'] = true;
    }
}

if (!$suspect && !$missing && !$errors) {
    $message = '';
    foreach ($expected as $item) {
        if (isset($$item) && !empty($$item)) {
            $val = $$item;
        } else {
            $val = 'Not selected';
        }
        if (is_array($val)) {
            $val = implode(', ', $val); 
        }
        $item = str_replace(array('_', '-'), ' ', $item);
        $message .= ucfirst($item) . ": $val\r\n\r\n";
    }
    $message = wordwrap($message, 70);

    $mailSent = mail($to, $subject, $message, $headers, $authenticate);
    if (!$mailSent) {
        $errors['mailfail'] = true;
    }
}

It sounds like what you need is some Javascript to do the scrolling. 听起来您需要一些Java脚本来进行滚动。 I don't know if you're using jQuery or not, but it makes this fairly easy. 我不知道您是否使用jQuery,但这使此操作相当容易。 This Stack Overflow link describes a number of approaches to it, such as: 堆栈溢出链接描述了许多方法,例如:

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

and calling it like: 并像这样调用它:

$('#your-form').scrollView();

In addition to that, you might want to consider seeing if you can do any input validation BEFORE the form is submitted. 除此之外,您可能需要考虑在提交表单之前是否可以进行任何输入验证。 Check out HTML5's input patterns and required fields 查看HTML5的输入模式必填字段

I would put some javascript within your error php so that when that loads it runs the javascript thus scrolling to the correct location based on form ID 我会在您的错误php中放入一些javascript,以便在加载时运行javascript,从而根据表单ID滚动到正确的位置

DEMO http://jsfiddle.net/RbxVJ/2/ 演示http://jsfiddle.net/RbxVJ/2/

$(function() {
    $(document).scrollTop( $("#header").offset().top );  
});

Actually I would use pure javascript as you may not have called the jQuery library at this point 实际上,我会使用纯JavaScript,因为此时您可能尚未调用jQuery库

EDITED EDITED

Your PHP 您的PHP

DEMO http://jsfiddle.net/RbxVJ/430/ 演示http://jsfiddle.net/RbxVJ/430/

    <?php
    if(!isset($_GET['success'])) 
    {
        ?>
        <script>
        window.location.hash = '#your-form-ID';
        </script>
        <?php
    }
    ?>

If you are going to be using JavaScript to solve the problem, you might as well use it to validate your form rather/in addition to PHP. 如果要使用JavaScript来解决问题,则最好使用它来验证您的表单,而不是/除了PHP外。 It is quicker (avoiding the necessary refresh with PHP), and you should never find yourself in the position to have to reload the form in any way other than with a successful submission. 它更快(避免使用PHP进行必要的刷新),并且您永远不会以必须成功提交之外的任何方式重新加载表单。

Write a function that executes when the submit button is pressed that gathers the required fields, checks them for appropriate values, stops form submission if any are missing, and then, alters the HTML with reminder text next to those that 'broke the rules' as it were. 编写一个函数,该函数在按下“提交”按钮时执行,该函数会收集必填字段,检查它们是否为适当的值,如果缺少任何值,则停止表单提交,然后在“违反规则”的旁边加上提示文本来更改HTML,例如它是。

     $(document).ready(function(){
        $('#contactBox a[href="' + window.location.hash + '"]').click();
     });

I was having a similar issue. 我有一个类似的问题。 When the form on the current page was submitted I would reload the current page. 提交当前页面上的表单后,我将重新加载当前页面。 My form was at the bottom of the page, but when the page was reloaded the page would be scrolled to the very top again. 我的表单位于页面的底部,但是当重新加载页面时,页面将再次滚动到最顶部。 Reloading the current page is done with; 重新加载当前页面完成;

<form action="">

So if my form is on my index.html page, this is the same as; 因此,如果我的表单位于index.html页面上,则与;

<form action="index.html">

To solve the scrolling issue I gave the form element an id and then referenced this id in the 'action' attribute value, like so; 为了解决滚动问题,我给了form元素一个ID,然后在'action'属性值中引用了这个ID,就像这样;

<form id="contact-form" action="#contact-form">

Again if the form is on my index.html page, this is the same as; 同样,如果该表单在我的index.html页面上,则与;

<form id="contact-form" action="index.html#contact-form">

If you weren't aware, when you append an element id to the end of the web page URL, it will load that web page and scroll directly to that element. 如果您不知道,则在将元素ID附加到网页URL的末尾时,它将加载该网页并直接滚动到该元素。

If there are any concerns with this method please chime in. 如果对此方法有任何疑问,请发出提示。

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

相关问题 仅当用户来自该页面时,如何在提交表单后将 CodeIgniter 中的 URL 重定向回上一页? - How to redirect URL in CodeIgniter after form submission back to the previous page only when the user comes from that page? 提交表单后返回页面的一部分 - Return to a section of a page after form submission 如何从函数返回错误数组以形成页面 - How to return errors array from a function to form page ajax的返回值返回0 - return value on ajax comes back with 0 根据要求返回特定部分 - Return a certain section on request 如何验证请求是否来自PHP中的某个网关? - How to validate that a request comes form a certain gateway in PHP? 在 Laravel 中,如何验证所有输入字段,如果有错误消息显示,如果有错误,则返回带有输入的表单 - In Laravel ,how to validate all the input fields, display error messages if any, and return back to the form with the inputs if there are errors 如何在刷新页面或单击后退按钮时阻止表单重新提交 - How to Prevent Form Resubmission when page is refreshed or back button is clicked 重定向进行处理时如何通过$ _POST将表单错误发送回表单 - How to send form errors back to the form via $_POST when redirected for processing WooCommerce:当客户离开然后回来时如何保留结账信息? - WooCommerce: How to retain checkout info when client leaves then comes back?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM