Need to add simple form submission confirmation to your forms? Alpine.js allows you to handle this with a few lines of code!
To start, here's a basic form that we'll be adding the confirmation to:
<form action="{{ route('comments.destroy', $comment) }}" method="post">
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
Because this is a destructive action, adding a confirmation to this form makes sense.
Let's stick to native browser confirmations, and once you're done, switch it up if you need.
Here's the form with the required Alpine.js trigger to prompt the user to confirm:
<form
x-data
x-on:submit.prevent="if (window.confirm('Are you sure?')) { $el.submit() }"
action="{{ route('comments.destroy', $comment) }}"
method="post"
>
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</form>
What's happening here?
First, we add x-data
to initialize the form as an Alpine.js component. Don't worry if you have a parent component wrapped around this, it'll work in exactly the same way.
Next, we attach a submit
handler, preventing the default behavior (submitting the form)
Then, the snippet of code inside the handler prompts the user. If they accept, we run the block and use the magic $el
property in Alpine.js which references the current component element (the form).
From there, we submit()
the form!
I love this method of confirming form submissions with Alpine.js. It doesn't require much code, works well, and because it uses the native browser confirmation dialogue, it'll work everywhere. Generally, I'll start off a project with these native confirmations and only replace it out with a more custom solution later if required.