htmx Tutorial · Common Patterns · Lesson 18 of 30
Click to Edit
Show a record, swap in an edit form with one click, save with PUT, and cancel back to the view.
The pattern
- The page shows the record with an Edit button:
hx-get="/contact/1/edit". - The server returns a form that replaces the view (
hx-target="this"on the container,hx-swap="outerHTML"). - Save sends
hx-put="/contact/1"; the server saves and returns the view again. - Cancel fetches the view without saving.
The view and the form are two small templates on the server, and they swap with each other:
<div hx-target="this" hx-swap="outerHTML">
<p><strong>Name:</strong> Ada Lovelace</p>
<p><strong>Email:</strong> [email protected]</p>
<button hx-get="/contact/1/edit">Edit</button>
</div>
<!-- The pretend server: on a real site this part is your backend (Python, PHP, Node, Go...) -->
<script>
const contact = { name: "Ada Lovelace", email: "[email protected]" };
const view = () => `<div hx-target="this" hx-swap="outerHTML">
<p><strong>Name:</strong> ${server.escape(contact.name)}</p>
<p><strong>Email:</strong> ${server.escape(contact.email)}</p>
<button hx-get="/contact/1/edit">Edit</button></div>`;
server.get("/contact/1/edit", () => `<form hx-put="/contact/1" hx-target="this" hx-swap="outerHTML">
<label>Name <input name="name" value="${server.escape(contact.name)}"></label><br>
<label>Email <input name="email" type="email" value="${server.escape(contact.email)}"></label><br>
<button>Save</button> <button type="button" hx-get="/contact/1">Cancel</button></form>`);
server.put("/contact/1", (req) => { Object.assign(contact, req.body); return view(); });
server.get("/contact/1", view);
</script>
On a real server, the PUT handler validates the input; if something is wrong it returns the form again with
messages (see Forms and Validation).
Test yourself
In click-to-edit, what does the server return after a successful PUT?
The read-only view of the recordJSON with the saved fieldsAn empty responseThe edit form again
Show answer
Answer: The read-only view of the record
The view and form swap back and forth; after saving, the view replaces the form.