Home Posts Tags Post Search Tag Search

Post 16

Game Site Journal - 07

Published on: 2025-04-14 Tags: elixir, Blog, Side Project, LiveView, Game Site, Html/CSS, Buttons, Reset Forms
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.

Firs 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.

First add/update this to the .input for 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 (that we will make in second) 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. 

Last we need to be sure that we push the event to the socket with
{: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 to cursor to default to the Guess cell.

Okay now that that is done there is 2 ways that we could try and fix the issue with the cell clearing on submit first:

A little secret is that if the key changes LiveView will re-render the form so if you just add
<.input
        type="number"
        field={@form[:guess]}
        label="Guess"
        phx-hook="FocusGuess"
        key={@question}
      />

it will always re-render that cell

The other option is to use an other hook and be sure you add the phx-hook to the line. I didnt choose this one as I already have a hook on that input.

let Hooks = {}
Hooks.ClearGuess = {
  mounted() {
    this.el.value = ""
  },
  updated() {
    this.el.value = ""
  }
}

and 

<.input
  type="number"
  field={@form[:guess]}
  label="Guess"
  phx-hook="ClearGuess"
/>