Clear all input fields on submit using Hyperscript

2.4k Views Asked by At

I'm playing around with htmx and hyperscript, and I want all input fields in the form below to be cleared on submit:

<form hx-post="/example" hx-target="#table tbody" hx-swap="beforeend"
      _="<what should I write here??>">
        <label class="control-label" for="firstNameInput">First Name</label>
        <input id="firstNameInput" name="firstName" class="form-control" type="text" required placeholder="John"/>
        
        <label class="control-label" for="lastNameInput">Last Name</label>
        <input id="lastNameInput" name="lastName" class="form-control" type="text" required placeholder="Doe"/>
        <button class="btn btn-primary">Add User</button>
    </div>
</form>

I've tried replacing <what should I write here??> with e.g. on submit put '' into <input/> and on submit put '' into <input[value]/> and lots of other combinations but I fail to get this work.

Q: How can I clear all input fields when the form is submitted?

3

There are 3 best solutions below

2
On BEST ANSWER

Try with on htmx:afterRequest reset() me

0
On

You don't need hyperscript, htmx is enough.

hx-on::after-request="this.reset()"

This way you can reset the form after submitting it.

Example for Django (Python):

<form hx-post="{% url 'comment_add' post.id %}"
    hx-target="#tab-contents"
    hx-swap="afterbegin"
    hx-on::after-request="this.reset()">
    {% csrf_token %}
    {{ form }}
    <button type="submit">Отправить</button>
</form>
0
On

If you simply changing input directly, you do not need form or a reset input you can do it with on:htmx:<event> set my value to ''

<input 
   name="text" 
   hx-get="/processInput"
   hx-trigger="keyup[keyCode==13], text"
   hx-target=".output"
   _="on htmx:afterRequest set my value to ''">
</input>