hotwired / turbo

The speed of a single-page web application without having to write any JavaScript
https://turbo.hotwired.dev
MIT License
6.65k stars 421 forks source link

Turbo not waiting for confirm method #751

Closed leoplct closed 1 year ago

leoplct commented 1 year ago

Expected: The confirm dialog should prevent the form to be submitted because resove is false Actual: The confirm dialog is shown but the form is submitted without waiting for the answer

view.html.erb

<%=form_with url: url_for(action: :create), data: {"turbo-frame": "_top", "turbo-confirm": "Are you sure?"} do |f| %>
    <%=f.submit%>
<% end %>

dialog.js

Turbo.setConfirmMethod((message, element) => {

  let dialog = document.getElementById("turbo-confirm")
  dialog.querySelector("p").textContent = message
  dialog.showModal()

  return new Promise((resolve, reject) => {
    dialog.addEventListener("close", () => {

      //Removing disabled from submit
      element.querySelector('[type=submit]').removeAttribute('disabled')

      resolve(dialog.returnValue == "confirm")
    }, { once: true })
  })
})

layouts.html.erb

<dialog id="turbo-confirm">
    <form method="dialog">
        <div class="modal-body">
            <p>Are you sure?</p>
        </div>
        <div>
            <button value="confirm" class="btn btn-primary">Confirm</button>
            <button value="cancel"  class="btn btn-secondary">Cancel</button>
        </div>
    </form>
</dialog>

Gemfile gem 'turbo-rails', '>= 1.3.0', :git => 'https://github.com/hotwired/turbo-rails'

leoplct commented 1 year ago

SOLVED.

I had to upgrade package.json to "@hotwired/turbo": "^7.2.0",