htmx:confirm with custom event drop hx-vals parameters when triggered by htmx.trigger
If an event listener is placed on "htmx:confirm" and then a issueRequest() is made the custom event parameters are lost from the htmx.trigger. If the issueRequest() is commented out the parameters are correctly passed through.
I just want to confirm this is correct usage for having a condition in "htmx:confirm" to cancel a request or allowing it.
I haven't investigated why issueRequest is doing this, but I assume the default behaviour would be the calling of this function.
<!-- load demo environment -->
<script src="https://demo.htmx.org"></script>
<script>
document.body.addEventListener("htmx:load", function() {
htmx.trigger("#count", "count", { number: 10 })
})
document.body.addEventListener("htmx:confirm", async function (event) {
event.preventDefault()
// some condition to determine if the request will be made or cancelled
await event.detail.issueRequest()
})
</script>
<div
id="count"
hx-get="/counting"
hx-trigger="count from:body"
hx-target="#result"
hx-vals="js:{count: event.detail.number * 2 }">
Count Up
</div>
<output id="result"></output>
<template url="/counting">
${JSON.stringify(params)}
</template>
Hey, that sounds like a bug indeed Looking at the code, there's this part: https://github.com/bigskysoftware/htmx/blob/0f70de7c0f8da72b3667fa7aef44636e51caf94e/src/htmx.js#L4090-L4094
So I would expect it to let you do the exact same request it would've made if called directly, which is indeed not happening as expected on your example code above.
I don't know off the top of my head where that could come from, so if you feel like investigating, a bugfix PR would be very welcome!
This may not be bug, but the incorrect usage of the Htmx:confirm. I have noticed in the documentation references to using it as a listener vs a call back.
document.body.addEventListener("htmx:confirm",....)
or using the call back.
htmx.on("htmx:confirm", async (event) => {})
The second one produces the correct result the first fails. If it should produce the same result then it is a bug.
htmx.on should just be a handy helper function, and is supposed to resolve to a standard addEventListener under the hood, that definitely sounds weird if it works while a direct addEventListener doesn't 😮
If it should produce the same result then it is a bug.
I'd say it's a bug indeed then
When confirm is not used, the event in hx-vals is the count event.
When confirm is used, the event in hx-vals is the htmx:confirm event.
To access the number value in hx-vals for the htmx:confirm event, you would use:
event.detail.triggeringEvent.detail.number