我正在对表单进行简单的验证。 JavaScript 验证工作正常,弹出警告框显示正确的错误,但是,单击“确定”后,我被重定向到下一页。理想情况下,它应该停留在同一页面上,以便用户可以修改他/她的错误。
这是一个学校项目。
<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>
最佳答案
这应该很容易修复。在表单标记的 onsubmit 方法中,执行以下操作:
<form onsumbit="return show_alert();">
代替
<form onsumbit="show_alert();">
如果没有 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>
关于JavaScript 表单错误状态不会停留在同一页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4769340/