David Wilkinson

Joined

3,510 Experience
35 Lessons Completed
0 Questions Solved

Activity

Another great episode, thanks! :)

For anyone else exploring Stimulus a bit more, an alternative to re-focusing the input element after submitting the form would be to use a static target in the Stimulus controller. IMO it feels more intuitive to clearly specify the target when we define the controller, rather than find it later by some other attribute like its autofocus property.

# reset_form_controller.js
export default class extends Controller {
  static targets = ["input"] # define the target here

  reset() {
    this.element.reset()
    this.inputTarget.focus() # use the target here
  }
}
# links/_form.html/erb

<%= form_with(model: link, ...[truncated]... }) do |form| %>
    <%= form.url_field(:url, ..., data: { reset_form_target: "input" }) %>  #  link the HTML element to the controller target here

    <%= form.submit "Save", ... %>
<% end %>

Earn XP by completing lessons, posting on the forum, and answering forum questions