HTMX may not have the capability to do this by default, but an extension has been created that adds new 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;
}
}
});
This extension can be used like so:
<body hx-ext="ask">
<a href="#" hx-ask="Type your age" hx-ask-default="69" hx-get="/set/age">My Age: ?</a>
</body>
When both hx-ask
and hx-prompt
are used together, only the result of hx-ask
will be sent as it runs later in the process.
This additional feature could be a valuable addition to the official hx-prompt
functionality with a pull request.