How to clear a textbox after submit

Thank you in advance.

I am learning. I am using Livieview. I am not using changeset. I am using HTML rather than Liveview <%= %> for this exercise.

The question is, how do I clear the textbox after I press enter or click the button to submit?


<form action="#" phx-submit="add" id="new_submit">
    <input type="text" name="text" placeholder="Add new record">
    <button type="submit">Add</button>
</form>

def handle_event("add", %{"text" => value}, socket) do
    SalesModule.Data.create_new(value)

    {:noreply, socket}
end
1 Like

This is “normally” handled by adding a fresh changeset when its submitted. Since you dont use it, I would use js attached to the onsubmit.

We definitely don’t need JS for this, but we do need to add a phx-change so that the liveview has more control over the form:

In your mount, add an assign called `text_value

|> assign(:text_value, nil)

Then update your form to have a phx-change, and set the value of the text field on the basis of the assign:

<form action="#" phx-submit="add" phx-change="change" id="new_submit">
    <input type="text" name="text" placeholder="Add new record" value={@text_value}>

Finally, we need to update the event handling clauses:

def handle_event("change", %{"text" => value}, socket) do
  socket = assign(socket, :text_value, value)
  {:noreply, socket}
end
def handle_event("add", %{"text" => value}, socket) do
    SalesModule.Data.create_new(value)
    socket = assign(socket, :text_value, nil)
    {:noreply, socket}
end

Basically the idea here is that we’re setting up the HTML to be derived from the assign, so that when on submit we set the assign to nil, the value goes away. This does require (or at least, is works best when) we also track all of the form changes along the way.

7 Likes

Its true. Its more than one way to skin a cat.

Thank you! This works.

Very nice and straightforward answer.

For completeness: option to add phx-throttle on the input: Bindings — Phoenix LiveView v1.0.1

Clearing the field without a changeset set is probably something that is frequently needed for things like a live chat - which is very simple to do in liveview with pubsub, so personally I add it almost everywhere.

I use the same approach as @benwilson512 described, but add a phx-throttle on the input, to get an event as soon as someone starts typing, but rate limit the updates afterwards.

If the change tracking is only needed to clear the field on submit, one can even use a throttle value that is quite high, because to clear the field liveview only needs to know that the value changed from anything to nil.

1 Like