LiveView phx_click confirm alert

phoenix
troubleshooting
liveview
#1

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?

#2

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.

2 Likes
#3

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

#4

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!

4 Likes
#5

Thank you!

#6

image