简体   繁体   English

提交表单前使用确认对话框的正确方法

[英]Correct way of using a confirm dialog Box before submit form

what is the correct way of using the confirm dialog box before the submit form? 在提交表单之前使用确认对话框的正确方法是什么? I see two problem in my implementation, but can´t find solution. 我在实现中看到两个问题,但是找不到解决方案。
1)I show a dialog box while submitting. 1)我在提交时显示一个对话框。 I am using a global variable "val" in ShowConfirmation, this is not visible outside the ShowConfirmation function. 我在ShowConfirmation中使用了全局变量“ val”,在ShowConfirmation函数外部不可见。 If I use debugger, "val" is undefined in ".Submit" function. 如果使用调试器,则“ .Submit”函数中未定义“ val”。
2)Because i have "e.preventDefault" the form is not submitted. 2)因为我有“ e.preventDefault”的形式没有提交。 Forcing "submit" in function ShowConfirmation does not submit the form. 在函数ShowConfirmation中强制“提交”不提交表单。

<input type="submit" class="button" value="CONFIRM" onclick="Confirm())">
<Script>
var val;
$("#form").submit(function(e)
{
  // confirmation popup
  e.preventDefault();

  if (val==true)
  {
  // Do something
  }

})

ShowConfirmation(val) {
var r = confirm("Press a button");
if (r == true) {
  console.log("you pressed ok");
  .....
  val=true;
  $("#form").submit();
}
else {
  console.log("you pressed cancel");
  }
}
Confirm() {
...
...
ShowConfirmation(val);
}
</Script>

Hope the following code helps: 希望以下代码有帮助:

 $("#form").submit(function() { if (confirm("Press a button")) { // Do something console.log("you pressed ok"); $(this).off("submit").submit(); } else { console.log("you pressed cancel"); } return false; }) 

If you listen to the submit and then call it back (using $(this).submit()) you will join an endless loop which can be stopped just by not pressing ok on the confirm box. 如果您先听提交然后回叫(使用$(this).submit()),您将加入一个无限循环,只需在确认框上不按OK,就可以停止循环。

Instead of all your functions, the situation is actually very easy. 除了所有功能之外,情况实际上非常简单。

HTML (Example): HTML(示例):

<form id="form">
    <input type="submit" value="confirm" />
</form>

Javascript: 使用Javascript:

$('#form').click(function (e) {
   e.preventDefault();
    confirm("Are you sure?") ? $(this).submit() : alert("ok..");
});

Instead of using variables and stuff like that, we just want to check if the user confirmed or not, therefore we are using the comfortable ternary operator: 与其使用变量和类似的东西,我们只想检查用户是否确认,因此我们使用舒适的三元运算符:

confirm("Are you sure?") ? $(this).submit() : alert("ok..");

if the user confirms, it will submit the form, else it will alert ok. 如果用户确认,它将提交表单,否则将提示“确定”。 If you have two functions, just declare them correctly , you are missing the function before your function names. 如果您有两个函数,只需正确地声明它们,函数名之前就会缺少该函数

fiddle: http://jsfiddle.net/1jkyuez8/1/ 小提琴: http//jsfiddle.net/1jkyuez8/1/

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

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