JavaScript 表单错误状态不会停留在同一页面上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4769340/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript form error state does not stay on same page
提问by Chandni
I'm doing a simple validation for a form. The JavaScript validation works fine and the pop up alert box appears with the correct errors, BUT, upon clicking "Ok", I get re-directed to the next page. Ideally, it is supposed to stay at the same page so that the user can amend his/her mistakes.
我正在对表单进行简单的验证。JavaScript 验证工作正常,弹出警告框显示正确的错误,但是,单击“确定”后,我被重定向到下一页。理想情况下,它应该停留在同一页面,以便用户可以修改他/她的错误。
This is a school project.
这是一个学校项目。
<script type = "text/javascript">
function show_alert() {
    if (document.getElementById('time1').value == document.getElementById('time2').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == document.getElementById('time3').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == document.getElementById('time4').value) alert("ERROR! You cannot book the same timing twice!")
    else if (document.getElementById('time1').value == "0") alert("ERROR! You cannot leave the first time slot blank!")
    else {}
} 
</script>
回答by Jeremy Vanderburg
This should be easy to fix. In the onsubmit method of your form tag, do this:
这应该很容易解决。在表单标签的 onsubmit 方法中,执行以下操作:
<form onsumbit="return show_alert();">
Instead of
代替
 <form onsumbit="show_alert();">
Without the returnpart, the script will run, and the form will be submitted anyhow.  Also, if there is an error condition in the script, you need to add a return false;otherwise the form will still be submitted, and return true;if there is no error.  You can edit the script like so:
如果没有该return部件,脚本将运行,并且无论如何都会提交表单。另外,如果脚本中有错误情况,则需要添加一个,return false;否则表单仍然会被提交,return true;如果没有错误。您可以像这样编辑脚本:
<script type = "text/javascript">
function show_alert() {
    if (document.getElementById('time1').value == document.getElementById('time2').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time3').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == document.getElementById('time4').value) {
        alert("ERROR! You cannot book the same timing twice!");
        return false;
    } else if (document.getElementById('time1').value == "0") {
        alert("ERROR! You cannot leave the first time slot blank!");
        return false;
    } else {
        return true;
    }
} 
</script>

