简体   繁体   中英

Sweet alert - unable to add success sweet alert to simple form submit

**

 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> 

I've attempted to make a form with a submit button to add a task to an index page. On the submit i want a success sweet alert. however the alert first disappeared after milliseconds but that was resolved with a preventdefault(). But now the submit doesnt actually work anymore. any ideas? (I have imported things properly, just didnt add it in the snippet)

You need to define event . You can use swal 's .then to submit the form if the user clicked Ok .

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

  });
 event.preventDefault()
});

Demo:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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