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.

Create a free account to save this page, take notes and track your progress. Sign in

The pattern

  1. The page shows the record with an Edit button: hx-get="/contact/1/edit".
  2. The server returns a form that replaces the view (hx-target="this" on the container, hx-swap="outerHTML").
  3. Save sends hx-put="/contact/1"; the server saves and returns the view again.
  4. Cancel fetches the view without saving.

The view and the form are two small templates on the server, and they swap with each other:

Edit a contact in placeTry it yourself
<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?

  1. The read-only view of the record
  2. JSON with the saved fields
  3. An empty response
  4. The 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.

Was this page helpful?