Edit in Place
This pattern shows how to edit a record in place, without a page refresh.
It works by providing two modes that the user can switch between: View Mode & Edit Mode.
1. View Mode
In view mode, display the current value(s) with a way to switch to Edit Mode (e.g. a button / icon / etc.).
<div hx-target:inherited="this">
<p>Name: <span>{{ user.name }}</span></p>
<!-- On click, switch to edit mode -->
<button hx-get="/users/1/edit"
hx-swap="outerHTML">
Edit
</button>
</div>
The <button> GETs the edit form & replaces the parent <div> with it.
2. Edit Mode
In edit mode, show a form with Save & Cancel options.
<!-- On submit, save changes & return to view mode -->
<form hx-put="/users/1"
hx-target:inherited="this"
hx-swap:inherited="outerHTML">
<p>Name: <input name="name" value="{{ user.name }}" autofocus></p>
<button type="submit">
Save
</button>
<!-- On click, return to view mode (without saving) -->
<button type="button" hx-get="/users/1">
Cancel
</button>
</form>
The form PUTs the updated value to the server, which returns the updated view mode HTML to replace the form.
Note:
The endpoints follow REST conventions:
GET /users/1- Retrieve the current viewGET /users/1/edit- Retrieve the edit formPUT /users/1- Update the resource
The URL represents the resource (/users/1), and the HTTP method indicates the action.