用JS取消表单提交

时间:2018-05-23 10:27:22

标签: javascript html submit

为了论证,让我们说这是我的代码。



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>
&#13;
&#13;
&#13;

当用户按取消时,如何停止提交表单?

感谢

1 个答案:

答案 0 :(得分:2)

您需要从onclick函数返回true或false值。

这意味着您需要修改onclick函数和the_delete函数。

&#13;
&#13;
function the_delete() {

  if (confirm('Delete your Account')) {
    alert("Account Deleted, Redirecting to homepage");
    return true;
  } else {
    return false;
  }

}
&#13;
<form method="post" action="my-account/settings/delete-account">
  <button class="btn" onclick="return the_delete()">Delete Account</button>
</form>
&#13;
&#13;
&#13;

现代JavaScript(针对比Internet Explorer 8更现代的浏览器)将使用JavaScript绑定事件处理程序并改为操纵事件对象。

&#13;
&#13;
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);
&#13;
<form method="post" action="my-account/settings/delete-account">
  <button class="btn">Delete Account</button>
</form>
&#13;
&#13;
&#13;