我正在对表单进行简单验证。 javascript验证工作正常,弹出警告框出现正确的错误,但是,点击“确定”后,我会重新定向到下一页。理想情况下,它应该保持在同一页面,以便用户可以修改他/她的错误。请尽快帮助,这是一个学校项目,截止日期为3天! :(提前致谢。
<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>
答案 0 :(得分:3)
这应该很容易修复。在表单标记的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>