重置用户输入

此示例展示了如何使用 hx-on 轻松重置用户输入,允许用户发出多个请求,而无需手动删除他们之前的输入。

¥This example shows how to easily reset user inputs using hx-on, allowing users to make multiple requests without having to manually delete their previous inputs.

内联脚本将在 afterRequest 事件上运行,并确保只要响应具有 20x 状态代码,表单就会重置为其初始状态:

¥The inline script will run on the afterRequest event and ensures that the form will reset to its initial state as long as the response has a 20x status code:

<form hx-post="/note"
      hx-target="#notes" 
      hx-swap="afterbegin"
      hx-on::after-request="if(event.detail.successful) this.reset()">
    <div class="form-group">
        <label>Add a note</label>
        <input type="text" name="note-text" placeholder="blank canvas">
    </div>
    <button class="btn">Add</button>
</form>
<ul id="notes"><!-- Response will go here --></ul>

reset() 方法仅适用于 form 元素。对于其他元素,可以明确选择输入值并将其重置为默认值以实现相同结果。以下代码在功能上是等效的:

¥The reset() method is only available on form elements. For other elements, the input value can explicitly selected and reset to a default to achieve the same result. The following code is functionally equivalent:

<div>
    <label>Add a note</label>
    <input id="note-input" type="text" name="note-text" placeholder="blank canvas">
</div>
<button class="btn primary" 
        hx-post="/note" 
        hx-target="#note" 
        hx-swap="afterbegin" 
        hx-include="#note-input"
        hx-on::after-request="if(event.detail.successful)
            document.getElementById('note-input').value = ''">
    Add
</button>
<ul id="notes"><!-- Response will go here --></ul>
Server Requests ↑ Show

🔗Demo