简体   繁体   English

我尝试对 Node.js 删除表单实施 Sweet Alert

[英]I try to implement Sweet Alert to Node.js delete form

I'm trying to implement Sweet Alert to Node.js delete form, but unfortunately the alert doesn't work properly.我正在尝试对 Node.js 删除表单实施 Sweet Alert,但不幸的是警报无法正常工作。 It only pops up for a second and without clicking on delete button on the alert window, it deletes file from DB.它只弹出一秒钟,没有点击警报窗口上的删除按钮,它会从数据库中删除文件。

Here is my code:这是我的代码:

<form action="/comicbooks/<%= comicbook._id %>/?_method=DELETE" 
  method="POST" class="deleteForm" onsubmit='swal({
  title: "Are you sure?",
 text: "Your will not be able to recover this imaginary file!",
 type: "warning",
 showCancelButton: true,
 confirmButtonClass: "btn-danger",
 confirmButtonText: "Yes, delete it!",
 closeOnConfirm: false,
 showLoaderOnConfirm: true,
 },
function (isConfirm) {
 location.reload();
});'>  
<button class="btn btn-xs btn-danger">Delete</button>
</form>

Coul you please assist?你能帮忙吗?

Many thanks in advance, Szymon非常感谢, Szymon

You have two problems.你有两个问题。

  1. When the submit button is clicked, you want to display the alert, but you don't want the form to submit.单击提交按钮时,您希望显示警报,但不希望表单提交。 You've done nothing to prevent the form from submitting.您没有采取任何措施来阻止表单提交。
  2. When the alert has the OK button clicked, you want to submit the form, but you are reloading the current page instead.当警报单击确定按钮时,您想要提交表单,但您正在重新加载当前页面。

So, sort out the submit button first.所以,先整理一下提交按钮。

Don't use the onsubmit attribute.不要使用onsubmit属性。 It is more trouble than it is worth.这比它的价值更麻烦。

document.querySelector("form").addEventListener("submit", function (event) {
    event.preventDefault(); // Stop normal form submitting
    // Then include your code for showing the alert
});

Then make the alert do what you want when the OK button is selected.然后在选择“确定”按钮时使警报执行您想要的操作。

function (isConfirm) {
    document.querySelector("form").submit();
})

I finally found a bug in above code and now it is working perfectly in EJS file.我终于在上面的代码中发现了一个错误,现在它在 EJS 文件中完美运行。 There should be:应该有:

function archiveFunction(event) {
  event.preventDefault(); // prevent form submit
  var form = event.target.form; // storing the form
  swal({
      title: "Are you sure you want to delete the comicbook?",
      text: "You will not be able to undo this action.",
      type: "warning",
      showCancelButton: true,
      confirmButtonColor: "#DD6B55",
      confirmButtonText: "Delete",
      cancelButtonText: "Cancel",
      closeOnConfirm: false,
      closeOnCancel: false
    },
    function (isConfirm) {
      if (isConfirm) {
      form.submit();          // submitting the form when user press yes
      } else {
        swal("Cancelled", "Your comicbook has not been deleted.", "error");
      }
    });
}

Cheers, Szymon干杯,席蒙

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

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