htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Proposal: disable-element extension handles multiple elements from CSS selector

Open ehenighan opened this issue 2 years ago • 1 comments

Kind of goes hand in hand with https://github.com/bigskysoftware/htmx/issues/1491 really - the disable-element extension for when a request is in flight accepts a CSS selector, but if you used e.g. a class name in that selector you could potentially find multiple target elements.

Use case is, I might want to disable multiple other actions (e.g. buttons) while my request is in flight, not just a single one by ID.

ehenighan avatar Jun 13 '23 12:06 ehenighan

I use https://htmx.org/extensions/loading-states/ for similar things.

andryyy avatar Jun 13 '23 13:06 andryyy

The needed change should be pretty simple. In the current state, the extension uses querySelector to select the first that matches the selector. Instead querySelectorAll could be used like this:

"use strict";

// Disable Submit Button
htmx.defineExtension('disable-element', {
    onEvent: function (name, evt) {
        let elt = evt.detail.elt;
        let target = elt.getAttribute("hx-disable-element");
        let targetElements = (target == "self") ? [elt] : document.querySelectorAll(target);

        targetElements.forEach((targetElement) => {
            if (name === "htmx:beforeRequest" && targetElement) {
                targetElement.disabled = true;
            } else if (name == "htmx:afterRequest" && targetElement) {
                targetElement.disabled = false;
            }
        })
    }
});

EDIT: there is already a pull request #1650 that implements this change

GPla avatar Sep 10 '23 20:09 GPla