此演示展示了如何实现一种常见的模式,即选择行然后批量更新。这是通过将表单放在表格周围,在表格中包含复选框,然后在表单提交(POST
请求)中包含选中的值来实现的:
¥This demo shows how to implement a common pattern where rows are selected and then bulk updated. This is
accomplished by putting a form around a table, with checkboxes in the table, and then including the checked
values in the form submission (POST
request):
<form id="checked-contacts"
hx-post="/users"
hx-swap="innerHTML settle:3s"
hx-target="#toast">
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Active</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>Joe Smith</td>
<td>joe@smith.org</td>
<td><input type="checkbox" name="active:joe@smith.org"></td>
</tr>
...
</tbody>
</table>
<input type="submit" value="Bulk Update" class="btn primary">
<output id="toast"></output>
</form>
服务器将根据复选框的值批量更新状态。我们用一条关于更新的小提示消息来通知用户,并使用 <output>
元素礼貌地宣布更新以实现可访问性。请注意,<output>
元素适用于宣布特定表单中操作的结果,但如果你需要宣布与表单无关的通用消息,则使用 ARIA 实时区域(例如 <p id="toast" aria-live="polite"></p>
)是有意义的。
¥The server will bulk-update the statuses based on the values of the checkboxes.
We respond with a small toast message about the update to inform the user, and
use an <output>
element to politely announce the update for accessibility. Note
that the <output>
element is appropriate for announcing the result of an action
in a specific form, but if you need to announce general-purpose messages that are
not connected to a form it would make sense to use an ARIA live region, eg
<p id="toast" aria-live="polite"></p>
.
#toast.htmx-settling {
opacity: 100;
}
#toast {
background: #E1F0DA;
opacity: 0;
transition: opacity 3s ease-out;
}
很酷的是,由于 HTML 表单输入已经管理了自己的状态,因此我们不需要重新渲染用户表的任何部分。活动用户已经选中,不活动用户未选中!
¥The cool thing is that, because HTML form inputs already manage their own state, we don’t need to re-render any part of the users table. The active users are already checked and the inactive ones unchecked!
你可以在下面看到此代码的工作示例。
¥You can see a working example of this code below.