LiveView phx_click confirm alert

Hello all!

I am testing out live view, and have a button as follows:

<%= link “DELETE” to: “#”, phx_click: “delete_row”, phx_value: row.id, data: [confirm: “Are you sure?”] %>

However, live view ignores the confirm alert and and the code behind “delete_row” runs every time causing the row to, well, delete! I think I understand why this is happening, but has anyone found a way to make the native confirm alert work with phx_click?

1 Like

This is a workaround, just add an IIFE to the onclick event to call the confirmation alert:

<%= link “DELETE” to: “#”, phx_click: “delete_row”, phx_value: row.id, onclick: "(function(){ if (!confirm('Are you sure?')) {event.stopImmediatePropagation();} }).call(event)" %>

if cancel is clicked, then the function event.stopImmediatePropagation is invoked which stops the rest of the event handlers attached to the same element for the same event type from being executed, i.e. it prevents the phx-click handler to be called.

3 Likes

<button data-confirm="Are you sure?" phx-click="delete_row">DELETE</button> also works

12 Likes

This should work fine today on latest LiveView and phoenix_html. Update both deps and make sure you import "phoenix_html" in your app.js and then you’re good to go!

10 Likes

Thank you!

image

4 Likes

I am getting this same behaviour with the latest phoenix (1.6.0-rc.1) and live view (0.16.3). The confirmation dialog gets triggered but the event fires right away as well, before the confirmation dialog is closed.

@albydarned I have a little C3P0 statue on my desk. You press a button and he recites a quote from the movies. I hadn’t pressed it in a long time, but I did so this very morning and this is the exact quote he said, “Thank the Maker!”

And wouldn’t you know, it’s the last thing I read today at work before heading out – your meme! Too funny!

1 Like