Focus the first invalid field on a form with Rails 5 and simple_form gem

I am using Rails 5 and a simple_form gem with bootstrap pre-configured during installation (if that matters).

The problem is this: at the first stage of form visualization, the first field with an error should be focused. In case there are no errors, concentrate the first line.

This gemstone can be used autofocus: truefor fields, but placing this attribute in each field as a form destroys the simplicity of "simple_form". The only solution I found was to override the check of the autofocus field attribute and force it to set when the field has an error and the autofocus attribute is not set:

module SimpleForm
  module Helpers
    module Autofocus
      private

      def has_autofocus?
        options[:autofocus] == true || has_errors?
      end
    end
  end
end

, , :

= simple_form_for object do |f|
  = f.input :to, autofocus: true
  = f.input :cc
  = f.input :subject
  = f.input :body, input_html: {rows: 10}

, , , getter? ( JS, , HTML). (, , simple_form config/initializers), , ? , , ?

+4

Source: https://habr.com/ru/post/1679977/


All Articles