【问题标题】:Even after clicking cancel the form gets submitted即使在单击取消后,表单也会被提交
【发布时间】:2018-06-07 06:35:14
【问题描述】:

我正在提交表单,我正在显示一个确认框,询问用户他们是否真的想继续。但即使用户点击取消,表单仍然会被提交。

 <form onsubmit="return confirm('If you enter the incorrect number, the search will still be conducted and charge you for the cost of the search. do you want to continue?.')" action="http:example.com/" id="customersearch" name="customersearch" role="form" method="post" accept-charset="utf-8" novalidate="novalidate">

我怎样才能避免这种情况?谁能告诉我当用户点击取消时如何阻止表单提交?

【问题讨论】:

  • 使用您的代码的 codepen/jsfiddle/plunker 等发布工作代码 sn-p。那将很容易调试。以上信息不充分
  • 将您的确认放入条件语句中,根据用户选择相应返回或阻止
  • 你是如何提交的?

标签: javascript html forms form-submit confirm


【解决方案1】:

@Akshay Vasu,尝试以下解决方案,您需要调用表单的 onsubmit 事件

function validateForm() {
   if(confirm('If you enter the incorrect number, the search will still be conducted and charge you for the cost of the search. do you want to continue?.'))
   {
      $("myform").submit();
      
   }
   else{
     alert("Invalid");
     return false;
   }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

【讨论】:

  • 是的,这是工作示例。(使用 jquery)。但是问题中使用的方法有什么问题?
  • @Tanmay,为此我们需要检查他没有粘贴的 html 页面。但这是提交表单的全局解决方案,所以我会相应地回答。
  • 您的代码运行良好。谢谢你。就我而言,我使用的是引导程序,引导程序验证以某种方式影响了我的提交。现在解决了。
【解决方案2】:

这是工作代码 sn-p 您的代码也可以正常工作:

 <form onsubmit="return confirm('If you enter the incorrect number, the search will still be conducted and charge you for the cost of the search. do you want to continue?.')" action="http:example.com/" id="customersearch" name="customersearch" role="form" method="post" accept-charset="utf-8" novalidate="novalidate">
<input type="submit" value="submit">
</form>

【讨论】:

    【解决方案3】:

    随便放

    <button type="button">Cancel</button>
    

    取消,它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2021-01-08
      相关资源
      最近更新 更多