I am BARRY HESS > Blog

Rails Auto Select Text Field Tag

On a recent project, I needed to simulate the YouTube-ish text field selection box. You know the one where you can easily select and copy a link or embed code to send on to your friends. You click in the box, the text is automatically selected, and you can quickly copy the text.

I created a quite-simple helper for doing such things.

def auto_select_text_field_tag(name, value = nil, options = {})
  text_field_tag(name,
                 value,
                 { :onclick => "$('#{name}').select()",
                   :readonly => "true" }.merge(options))
end

Pretty easy when it’s all said and done. (It looks better on one line.)