How to add HTML5 auto focus to a rails form?

流过昼夜 提交于 2019-12-12 12:06:25

问题


I have a text field

  = text_field_tag('search_text_1', params[:search_text],
    options = {:type => 'search'} )

which generates

<input id="search_text" name="search_text_1" type="search">

that I want to add HTML5 autofocus to, as in

  = text_field_tag('search_text_1', params[:search_text], 
    options = {:type => 'search', :autofocus => true} )

This generates

<input autofocus="autofocus" id="search_text" name="search_text_1" type="search">

which does actually work, but how I can I get the actual HTML output for the autofocus to be as the HTML spec shows, i.e.

<input autofocus id="search_text" name="search_text_1" type="search" autofocus>
# Not sure where it goes or if that matters

Using

options = {:type => 'search', :autofocus } 

gives

.../_search.html.haml:2: syntax error, unexpected '}', expecting => 
...:type => 'search', :autofocus } )

As the HTML5 spec at https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input says, "which is a Boolean"


回答1:


If you’re willing to patch a private Rails method you can achieve the output you want. Rails writes out boolean attributes with the boolean_tag_option method in the TagHelper module which produces the autofocus='autofocus' format.

If you add the following to an initializer you can replace this method with one that writes out the attribute in the minimized format.

module ActionView::Helpers::TagHelper
  private def boolean_tag_option(key)
    key
  end
end

Obviously you need to be careful when upgrading the version of Rails your app is using. This method seems fairly stable at the moment, it is still there in 4.2.0.beta.1 and master.




回答2:


I ended up going with

= text_field_tag('search_text_1', 
  params[:search_text], 
  options = {:type => 'search', :autofocus => true })

and accepting the output of autofocus='autofocus'



来源:https://stackoverflow.com/questions/26049331/how-to-add-html5-auto-focus-to-a-rails-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!