JavaScript 表单错误状态不会停留在同一页面上

标签 javascript popup alert

我正在对表单进行简单的验证。 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/

相关文章:

javascript - 如何使用警告框确认单选按钮选择

javascript - 带有 express 和 react 的 Node.js,fs.readdir 找不到文件

javascript - JSON 字符串化 : Tabs in objects are converted to\t causing issue while upper casing the result

iphone - 如何在 iPhone 的 View 顶部显示弹出窗口

用于短信和电子邮件通知服务的 C# 代码

swift - 如何将用户数据传递给

javascript : creating elements on first click and deleting the created element on second click

javascript - 这是一个 'dead code' 即它只是多余的吗?

jquery - 如何在点击背景时关闭 ionic 弹出窗口

JQuery 移动弹出窗口 $.mobile.changePage 有错误吗?