dwyl / learn-phoenix

:fire: Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. :rocket:
649 stars 45 forks source link

How to autofocus an input in a Phoenix Form? #138

Open nelsonic opened 4 years ago

nelsonic commented 4 years ago

If you are writing a "traditional" Phoenix (without LiveView) App and want to autofocus an input this works:

<%= text_input f, autofocus: "true" %>

Note: the value of can be anything e.g: autofocus: "autofocus" works too as does autofocus: "" (empty string). We just prefer the value "true" for clarity in our code.

Whereas our 3 previous attempts don't work:

<%= text_input f, :autofocus %> # using an atom fails 
<%= text_input f, autofocus %> # using a keyword fails
<%= text_input f, "autofocus" %> # using a string fails

We read through https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html and did not find any reference to autofocus ... we read through https://elixirforum.com/t/phoenix-liveview-callbacks-to-put-text-input-focus-on-the-selected-input-field/21148 but that is specific to views rendered with LiveView.

If anyone is building a "traditional" Phoenix App as we are in https://github.com/dwyl/phoenix-todo-list-tutorial then this is the method that works.