[英]Why is my form submitted after cancelling the confirm dialog?
Here is my sample code: 这是我的示例代码:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function: 我在CheckData函数中有一些条件:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check: 然后我检查:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed. 因此,我需要前两个条件的确认对话框,否则,我不希望显示该对话框。
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form. 现在,当满足前两个条件之一时,将弹出确认对话框,但是当我单击“取消”时,它仍将提交表单。
Any suggestions? 有什么建议么?
PS: This code is a demo and different from the real one. PS:此代码是一个演示,与实际演示不同。 But the concept is the same. 但是概念是相同的。
Change your HTML to this: 将您的HTML更改为此:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation: 说明:
You can pass in the event
Object to the CheckData
function and prevent the default action if the confirm returns false with event.preventDefault()
. 您可以将event
Object传递给CheckData
函数,如果确认通过event.preventDefault()
返回false,则可以阻止默认操作。
<form> <button onClick="CheckData(event)" type="submit">Submit</button> </form> <script> function CheckData(e){ var warning; if (5<6) { warning = "sure?"; } else if (5>3) { warning = "really?"; } else { warning = ''; } if (warning.length>0) { var con = confirm(warning); if(con){ return true; } else { e.preventDefault(); return false; } } else { return true; } } </script>
You can also return
the result of CheckData
so the default action will be prevented if it returns false. 您还可以return
CheckData
的结果,因此如果默认操作返回false,则将阻止该默认操作。
<form> <button onClick="return CheckData()" type="submit">Submit</button> </form> <script> function CheckData(){ var warning; if (5<6) { warning = "sure?"; } else if (5>3) { warning = "really?"; } else { warning = ''; } if (warning.length>0) { var con = confirm(warning); return con; } else { return true; } } </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.