简体   繁体   English

使用JS取消表单提交

[英]Cancel a form submission with JS

for arguments sake let's say this is my code. 为了论证,让我们说这是我的代码。

 function the_delete() { if(confirm('Delete your Account')){ alert("Account Deleted, Redirecting to homepage"); } else { //Stop the submit } } 
 <form method="post" action="my-account/settings/delete-account"> <button class="btn" onclick="the_delete()">Delete Account</button> </form> 

How do I stop the form submitting when user presses cancel? 当用户按下“取消”时,如何停止提交表单?

thanks 谢谢

You need to return a true or false value from the onclick function. 您需要从onclick函数返回true或false值。

This means you need to modify both the onclick function and the the_delete function. 这意味着您需要同时修改onclick函数和the_delete函数。

 function the_delete() { if (confirm('Delete your Account')) { alert("Account Deleted, Redirecting to homepage"); return true; } else { return false; } } 
 <form method="post" action="my-account/settings/delete-account"> <button class="btn" onclick="return the_delete()">Delete Account</button> </form> 

Modern JavaScript (targetting browsers more modern than Internet Explorer 8) would bind event handlers with JavaScript and manipulate the event object instead. 现代JavaScript(针对比Internet Explorer 8更现代的浏览器)将事件处理程序与JavaScript绑定在一起,而是操纵事件对象。

 function the_delete(event) { if (confirm('Delete your Account')) { alert("Account Deleted, Redirecting to homepage"); } else { event.preventDefault() } } document.querySelector("form").addEventListener("submit", the_delete); 
 <form method="post" action="my-account/settings/delete-account"> <button class="btn">Delete Account</button> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM