Is there a way to assign a preset value to an HTMX prompt?

Is it possible to specify a default value when the window.prompt is displayed?

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

Currently, the window.prompt appears blank. Is there a way to set a predetermined age such as 20?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...

How can I retrieve the current active filters when using the DataGrid component from @material-ui/lab?

I'm currently working on integrating material-ui's data grid into one of my pages. The main objective is to capture the state of filters and sorts for all columns, and save them as a link at the top of the page. This way, users won't have to ...

An error has occurred: Unable to access the 'submit' property as it is undefined

When I inspect my website in Chrome, this is the HTML code that appears: <html> <head> <title>Please Wait</title> <link rel="shortcut icon" href="images/ajax-loader1.gif" type="image/x-icon"> < ...

Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button. ...

Merge two arrays by matching their corresponding identifiers

I have 2 separate arrays that I need to merge. The first array looks like this: const Dogs[] = [ { id: '1', name: 'Buddy' }, { id: '2', name: 'Max' }, ] The second one: const dogAges[] = [ { id: '4&ap ...

Ways to set the input=text field as read-only in JSP when receiving information from the backend

For a project I am working on, I need to implement a feature where users can view and edit their personal details on a JSP page. If a user is logged in, their information should be fetched from the session and displayed automatically. However, even if they ...

A pop-up blocker is preventing the new tab from opening

Below is my JavaScript code: $('#external-apply-job a').click(function(e) { var button = $(this); var url = $(this).data("system-url"); loadPreloader(); $.ajax({ url: url, ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

React error: Unexpected token < in JSON when fetching local file

I've encountered an issue with my React app. I have a JSON file in the public directory that I was successfully fetching data from in my main App.js file without any errors. However, after running `npm run build`, I started getting the error message: ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

Can the "value" of an HTML form field rendered by Django be altered?

Essentially, I have a form that includes a radio select widget for the field named Queue. The choices available for the Queue are sourced from a model, which is accessed and defined within the views.py file. To display this form on my template, I am using ...

The clearing of sessions is not supported by Node.js / Express.js

At the start, the application loads some users using Angularjs / $http.get(). As you scroll down, more users are loaded dynamically (infinite scroll). In addition to this, there are location filters on the page. Users can select a different Country and Ci ...

Changing all object values to true with React useState

In a certain file, I have defined an object with the following structure: export const items = { first: false, second: false, third: false } Within a component, I am using this object as shown below: import { items } from 'file'; const [el ...

Error encountered with AJAX call when attempting to utilize string method

I am looking to add HTML content to a TinyMCE editor in an ASP.NET MVC project. After some thought, I have found a solution that involves converting the HTML file to a string on the server side and then calling it using Ajax on the client side. Here is a ...

Tips for updating an existing project to the latest version of the Ajax toolkit

What is the most effective method for updating to a new version of Ajaxtoolkit within a preexisting project? ...

Error handling in Spring MVC's @ResponseBody annotation

I am encountering an issue with passing an entity GroupStudent object from my Spring Controller to a JSP page using an ajax function. When attempting to pass the GroupStudent object using @ResponseBody, I consistently receive an error in the browser: Error ...

Creating an interactive chart with Rickshaw that updates dynamically without the need to refresh the browser

My goal is to create a dynamic graph that continuously updates with fresh data without having to refresh the entire page. The example I found uses random data to build the graph, but the issue is that the data is not always up-to-date unless I manually ref ...

Determine whether a specific key exists in the formdata object

Can I check if a key in the formdata object already has a value assigned to it? I am looking for a way to determine if a key has been previously assigned a value. I attempted something like this but did not get the desired outcome data = new FormData(); ...