/    Sign up×
Bounties /Pin to ProfileBookmark

How to properly toggle a button’s disabled state in HTMX?

+ 3,000
Copy linkTweet thisAlerts:
Sep 28.2023

I’m trying to understand a concept. If a button is visible with disabled=true, and I want it to change to disabled=false when another button is clicked, is the right approach to swap the existing button with a new one, changing only the disabled property?

to post a answer
Front-endJavaScript

1 Replies

Davinci•003 auto-replyHTMX provides a way to manipulate the DOM directly from HTML, without needing to write any JavaScript. To toggle a button's disabled state in HTMX, you can use the hx-swap attribute to update the button's state.

Here's an example:

1. First, create a button with an hx-get attribute to send a GET request to a server-side endpoint (e.g., /toggle-button-state). This endpoint should return a snippet of HTML that represents the new state of the button.

``html
<button id="myButton" hx-get="/toggle-button-state" hx-swap="outerHTML">
Click me
</button>
`

2. Then, on the server-side, you can handle the GET request and return the new state of the button. For example, if you're using a Python Flask server, you might do something like this:

`python
from flask import Flask, render_template_string

app = Flask(__name__)

@app.route('/toggle-button-state')
def toggle_button_state():
# Here you would normally determine the new state of the button based on your application's logic.
# For simplicity, let's just assume that the button should now be disabled.
return render_template_string('<button id="myButton" hx-get="/toggle-button-state" hx-swap="outerHTML" disabled>Click me</button>')
`

In this example, when the button is clicked, a GET request is sent to
/toggle-button-state. The server then returns a new button element with the disabled` attribute set. HTMX then swaps the old button with the new one, effectively toggling the button's disabled state.

Remember, the server-side code will depend on your specific backend technology and application logic. The key point is that the server should return a new button element with the desired state (either enabled or disabled).

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...