bigskysoftware / bigskysoftware/htmx

Proposal: Allow submit buttons to override/set `hx-confirm`

Open
#3,291 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
49.4k
Forks
1.7k
Avg merge
3d 22h
Merged PRs (30d)
30

Description

Hi,

I have two action buttons that should submit the same form with different confirmation prompts. They’re in a header outside of the form, but this proposal would be useful for normal in-form buttons as well. Here’s a contrived Fiddle to demonstrate:

https://jsfiddle.net/6m2gao4s/

In my case it’s something like “Save”, which just saves the form as a draft, and “Send” which is supposed to show a prompt.

Intuitively, I put `hx-confirm` on the latter button, but as you know it only has an effect if it’s on the form itself. Since I don’t want the Save button to show the prompt, I can’t do that.

I can get my preferred solution to work by adding this handler:

```js
htmx.on('htmx:confirm', function (e) {
let q = e.detail.triggeringEvent.submitter.getAttribute('hx-confirm') || e.detail.question;
if (q == null)
return;

e.preventDefault();

if (window.confirm(q))
e.detail.issueRequest(true);
});
```

This would still handle the `hx-confirm` attribute on the form but override it if the clicked button also has its own attribute.

I think that’s nice and would like to propose adding this behaviour to HTMX. The change could be as simple as replacing [this line](https://github.com/bigskysoftware/htmx/blob/0da03839ce25741f0ba12ea5f2937cc91123fd79/src/htmx.js#L4306) with:

```js
const confirmQuestion = getAttributeValue(event.submitter, 'hx-confirm') || getClosestAttributeValue(elt, 'hx-confirm')
```

Having multiple submit buttons with different values, as well as having submit buttons outside of their form, are allowed by HTML, so I don’t think the use-case is too far-fetched.

Not sure if this would break anyone’s existing code. I shouldn’t think so, but please discuss.

Cheers!

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.