Javascript - 在警告消息后停止继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11664000/
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 - stop proceeding after alert message
提问by user1514499
In my web application, in the login page, I have a checkbox. After entering the username/password, if the user doesn't tick the checkbox (T&C), he should not be taken to the home page, and an alert error message will be shown.
在我的 Web 应用程序的登录页面中,我有一个复选框。输入用户名/密码后,如果用户没有勾选复选框(T&C),则不应将其带到主页,并会显示警告错误消息。
I have tried the following code. But it is not working. That is, an alert message is shown. But the user is taken to the next page(home page). I tried returning false, but no luck.
我试过下面的代码。但它不起作用。即,显示警报消息。但是用户被带到下一页(主页)。我尝试返回 false,但没有运气。
Can anyone tell how to fix this?
谁能告诉如何解决这个问题?
function doSubmit() {
var checkbox = document.getElementById("terms");
if (!checkbox.checked) {
alert("error message here!");
return;
}
document.getElementById("f").submit();
}?
I am calling doSubmit from
我正在调用 doSubmit 从
<input id="proceed" onclick="doSubmit()" type="submit" value="${fn:escapeXml(submit_label)}" />
回答by ddsh79
Instead of using onclick
in input, try using the below in the form tag:
不要onclick
在输入中使用,而是尝试在表单标签中使用以下内容:
onsubmit="return doSubmit()"
And the js functions as:
并且 js 的功能如下:
function doSubmit() {
var checkbox = document.getElementById("terms");
if (!checkbox.checked) {
alert("error message here!");
return false;
}
}
回答by jelies
Try changing the input type to buttoninstead of submit, delegating the submit action to JS function:
尝试将输入类型更改为button而不是submit,将提交操作委托给 JS 函数:
<input id="proceed" onclick="doSubmit()" type="button" value="${fn:escapeXml(submit_label)}" />
回答by xiaowl
Before you submit your form, you should check the checkbox
's status, if it's not checked, prevent the from from submit. In jQuery, the following code does the tricks.
在提交表单之前,您应该检查checkbox
的状态,如果未选中,则阻止 提交。在 jQuery 中,以下代码可以实现这些技巧。
$(form).submit(function(e){
if($(this).find("#terms").is('checked')){
e.preventDefault();
alert('error messge goes here');
}
}