4

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"

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497

2 Answers2

3

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.

matt
  • 78,533
  • 8
  • 163
  • 197
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'

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497