htmx/www/content/examples/confirm.md
matiboy 712ee759f1
Fix confirmed being ignored in htmx:confirm event (#1610)
* Current behavior testing

Testing current library behavior

* Test should remove correct handler

* Add question in htmx:confirm event detail

* Allow skipping window.confirm

* Additional test without hx-confirm value

* Wrap htmx.off in finally

* More correct assertion in case of no calls to confirm

* Remove erroneously added formatting

* Remove erroneously added formatting

* Documentation, fix loop

---------

Co-authored-by: mat <matt@techspace.asia>
2023-10-26 14:43:41 -06:00

3.8 KiB

+++ title = "A Customized Confirmation UI" template = "demo.html" +++

htmx supports the hx-confirm attribute to provide a simple mechanism for confirming a user action. This uses the default confirm() function in javascript which, while trusty, may not be consistent with your applications UX.

In this example we will see how to use sweetalert2 and the htmx:confirm event to implement a custom confirmation dialog. Below are two examples, one with hyperscript using a click+custom event method, and one in vanilla JS and the built-in hx-confirm attribute.

Hyperscript, on click+custom event

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<button hx-get="/confirmed" 
        hx-trigger='confirmed'
        _="on click
            call Swal.fire({title: 'Confirm', text:'Do you want to continue?'})
            if result.isConfirmed trigger confirmed">
  Click Me
</button>

We add some hyperscript to invoke Sweet Alert 2 on a click, asking for confirmation. If the user confirms the dialog, we trigger the request by triggering the custom "confirmed" event which is then picked up by hx-trigger.

Note that we are taking advantage of the fact that hyperscript is async-transparent and automatically resolves the Promise returned by Swal.fire().

A VanillaJS implementation is left as an exercise for the reader. :)

Vanilla JS, hx-confirm

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
  document.addEventListener("htmx:confirm", function(e) {
    e.preventDefault()
    Swal.fire({
      title: "Proceed?",
      text: `I ask you... ${e.detail.question}`
    }).then(function(result) {
      if(result.isConfirmed) e.detail.issueRequest(true) // use true to skip window.confirm
    })
  })
</script>
  
<button hx-get="/confirmed" hx-confirm="Some confirm text here">
  Click Me
</button>

We add some javascript to invoke Sweet Alert 2 on a click, asking for confirmation. If the user confirms the dialog, we trigger the request by calling the issueRequest method. We pass skipConfirmation=true as argument to skip window.confirm.

This allows to use hx-confirm's value in the prompt which is convenient when the question depends on the element e.g. a django list:

{% for row in clients %}
<button hx-post="/delete/{{client.pk}}" hx-confirm="Delete {{client.name}}??">Delete</button>
{% endfor %}

{{ demoenv() }}