We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
This is a post about making sure that a form is properly cleared for an html simple form, as well as making sure that the cursor is set to the right cell whenever you load into the page or refresh after a submit is sent.
First thing that I wanted to tackle is the cursor moving to the right place. It can be accomplished with a Hook and the right settings for the cell.
<.input type="number" field={@form[:guess]} label="Guess" value={@form.params["guess"] || ""} phx-hook="FocusGuess" />
This makes sure that if nothing is sent we default to "" and we call the right Hook (FocusGuess) when rendering the page.
Now head to app.js and add this:
Hooks.FocusGuess = {
mounted() {
this.el.focus()
this.el.select?.()
},
updated() {
this.el.focus()
this.el.select?.()
}
}
This makes sure that upon mounting or updating the page we select the element that is calling the Hook.
Push the event to the socket whenever you want the cursor to default to the Guess cell:
{:noreply,
assign(
socket
|> push_event("focus-guess", %{})
)}
or
{:noreply,
assign(
socket
|> put_flash(:info, "Score is 0 Resetting")
|> push_event("focus-guess", %{})
)}
We need to do this for every event that we want the cursor to default to the Guess cell.
There are two ways to fix the issue with the cell clearing on submit:
Option 1 (preferred) – add a key to force LiveView to re-render the form:
<.input
type="number"
field={@form[:guess]}
label="Guess"
phx-hook="FocusGuess"
key={@question}
/>
Option 2 – use a separate hook to clear the input:
Hooks.ClearGuess = {
mounted() {
this.el.value = ""
},
updated() {
this.el.value = ""
}
}
<.input
type="number"
field={@form[:guess]}
label="Guess"
phx-hook="ClearGuess"
/>