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

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.