JavaScript提醒错误消息
问题描述:
我正在做一个窗体的简单验证。 JavaScript验证工作正常,弹出警告框出现正确的错误,但点击“确定”后,我会重新定向到下一页。理想情况下,它应该保持在同一页面上,以便用户可以修改他/她的错误。请尽快帮助,这是一个学校项目,截止日期为3天! 。:(在此先感谢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;
否则表单仍将提交,并且01如果没有错误,则为。您可以编辑脚本,如下所示:
<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>
此外,`show_alert`需要返回true或false,指示是否应提交表单。 – casablanca 2011-01-22 17:27:25