Search code examples
javascriptajaxhtmx

How can I set a default value in an HTMX prompt?


I want to know how can I set a default value when window.prompt window is opened.

<a href="#" hx-prompt="Type your age" hx-get="/set/age">My Age: ?</a>

window.prompt is blank. How can I set predefined age like 20?


Solution

  • HTMX doesn’t let you do that, but here’s an extension that introduces the custom attributes hx-ask and (optionally) hx-ask-default:

    htmx.defineExtension('ask', {
        onEvent: function(name, event) {
            if (name !== 'htmx:configRequest')
                return;        
    
            const elt = event.detail.elt;
            const askElt = elt.closest('[hx-ask]') || elt.closest('[data-hx-ask]');
            
            if (askElt) {
                const question = askElt.getAttribute('hx-ask') || askElt.getAttribute('data-hx-ask');
                const suggestion = askElt.getAttribute('hx-ask-default') || askElt.getAttribute('data-hx-ask-default');
                const answer = prompt(question, suggestion || undefined);
    
                if (answer !== null) //null when canceled
                    event.detail.headers['HX-Prompt'] = answer;
            }
        }
    });
    

    To be called like this:

    <body hx-ext="ask">
        <a href="#" hx-ask="Type your age" hx-ask-default="69" hx-get="/set/age">My Age: ?</a>
    </body>
    

    As you can see, it sends the HX-Prompt header just like the hx-prompt attribute. If you use both hx-ask and hx-prompt, you’ll get two prompts, but only the result of hx-ask will be sent, because it runs later.

    Seems like a nice enough feature, someone should make a PR and add it to the official hx-prompt thing.