Alpine: [Bug?] Javascript confirm dialog cancel not working

Created on 30 Jan 2020  路  3Comments  路  Source: alpinejs/alpine

<form action="/documents/1" 
    method="POST"
    x-data
    onclick="return confirm('Move to trash?')"
    x-on:click="return confirm('Move to trash?')"
>
    <button type="submit">Delete</button>
</form>

The OG onclick="" is working as expected. OK continues the request, and cancel aborts the request.

The Alpine version however always continues the request, on both OK and cancel.

Might be me doing something wrong, but I can't seem to get it working. Any ideas?

Most helpful comment

Hmm, okay! Thank you for the answer!

I think I'll keep the native onclick behaviour for now, since it's shorter and simpler. And I don't need that component for anything else in Alpine.

Leaving this open until @calebporzio has seen it. Feel free to close if not doable, but it would be slick to have in Alpine, no? 馃槈

How about @click.confirm="Are you sure?"?

All 3 comments

That way of stopping an event is typical of vanilla JS but the documentation doesn't mention it so I wouldn't expect it to work.

The Alpine way for something like that would be:

  • stop the event using a modifier
  • submit the form when you get confirmation
<form action="/documents/1" method="POST" x-data x-ref="form">
    <button x-on:click.prevent="if (confirm('Move to trash?')) $refs.form.submit()" type="submit">Delete</button>
</form>

From the documentation:
x-on attaches an event listener to the element it's declared on. When that event is emitted, the JavaScript expression set as its value is executed.

Hmm, okay! Thank you for the answer!

I think I'll keep the native onclick behaviour for now, since it's shorter and simpler. And I don't need that component for anything else in Alpine.

Leaving this open until @calebporzio has seen it. Feel free to close if not doable, but it would be slick to have in Alpine, no? 馃槈

How about @click.confirm="Are you sure?"?

Yeah, I actually think mimicking normal return behavior in an onclick is handy.

It kinda goes with the ethos that Alpine should feel very native-eventy.

I'd be down for this and I *think it'd be a pretty simple implementation on this line: src/directives/on.js:37

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mrmathewc picture mrmathewc  路  4Comments

hkan picture hkan  路  3Comments

mikemartin picture mikemartin  路  3Comments

bep picture bep  路  4Comments

dkuku picture dkuku  路  5Comments