【问题标题】:Sweet alert - unable to add success sweet alert to simple form submit甜蜜警报 - 无法将成功甜蜜警报添加到简单的表单提交
【发布时间】:2018-09-24 20:36:09
【问题描述】:

**

function bindSweetAlertButtonDemo() {
  const swalButton = document.getElementById('sweet-alert-demo');
  if (swalButton) { // protect other pages
    swalButton.addEventListener('click', () => {
      swal({
        title: "Nice",
        text: "You've added a task. Click on it for more details",
        icon: "success"

      });

 event.preventDefault()


    });
  }
}
<div>
  <%= simple_form_for [ @task] do |f| %>
   <%= f.input :name %>
   <%= f.input :description %>
   <%= f.submit :submit, class: "btn btn-danger" ,id: "sweet-alert-demo" %>
  <% end %>

</div>

我试图制作一个带有提交按钮的表单,以将任务添加到索引页面。在提交时,我想要一个成功的甜蜜警报。然而,警报首先在几毫秒后消失,但通过 preventdefault() 解决了这个问题。但是现在提交实际上不再起作用了。有任何想法吗? (我已经正确导入了东西,只是没有在sn-p中添加)

【问题讨论】:

  • 你没有定义event应该是('click', (event) =&gt; ...
  • 您是否在 html 中添加 文件以进行甜蜜警报,能否请您提供错误以供我们检查

标签: javascript html ruby-on-rails sweetalert


【解决方案1】:

您需要定义event。如果用户点击了Ok,您可以使用swal.then 提交表单。

swalButton.addEventListener('click', (event) => {
  swal({
    title: "Nice",
    text: "You've added a task. Click on it for more details",
    icon: "success"

  });
 event.preventDefault()
});

演示:

const swalButton = document.getElementById('sweet-alert-demo'), form = document.querySelector('form');
function bindSweetAlertButtonDemo() {
  if (swalButton) { // protect other pages
    swalButton.addEventListener('click', (event) => {
      swal({
        title: "Nice",
        text: "You've added a task. Click on it for more details",
        icon: "success"

      }).then(function(value){
        if(value!=null){
        form.submit();
        }
      });
        event.preventDefault();
    });
  }
}
bindSweetAlertButtonDemo();
<script src="https://unpkg.com/sweetalert@2.1.0/dist/sweetalert.min.js"></script>
<div>
<form>
<input type="text" name="name" placeholder="Name"><br/>
<input type="description" name="description" placeholder="Description"><br/>
<button id="sweet-alert-demo">Submit</button>
</form>
</div>

【讨论】:

  • 谢谢,但是这仍然只能阻止警报显示一毫秒的问题。它现在已经阻止表单实际提交任务,内容就在输入框中。
  • @b.herring 您可以拨打document.getElementById('formid').submit()随时提交表单。
  • 对不起,我对此很陌生。那个'formid'是占位符吗?如果是,我如何将自己的 id 插入表单?
  • @b.herring 输入您的formid
  • 您是否在 html 中添加 文件以进行甜蜜警报,能否请您提供错误以供我们检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 2018-07-25
  • 1970-01-01
  • 2022-08-06
相关资源
最近更新 更多