Ruby on Rails: How do I add placeholder text to a f.text_field?

Ruby on-Rails

Ruby on-Rails Problem Overview


How can I add placeholder text to my f.text_field fields so that the text comes pre-written by default, and when a user click inside the fields, the text goes away - allowing the user to type in the new text?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

With rails >= 3.0, you can simply use the placeholder option.

f.text_field :attr, placeholder: "placeholder text"

Solution 2 - Ruby on-Rails

In Rails 4(Using HAML):

=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'

Solution 3 - Ruby on-Rails

For those using Rails(4.2) Internationalization (I18n):

Set the placeholder attribute to true:

f.text_field :attr, placeholder: true

and in your local file (ie. en.yml):

en:
  helpers:
    placeholder:
      model_name:
        attr: "some placeholder text"

Solution 4 - Ruby on-Rails

I tried the solutions above and it looks like on rails 5.* the second agument by default is the value of the input form, what worked for me was:

text_field_tag :attr, "", placeholder: "placeholder text"

Solution 5 - Ruby on-Rails

Here is a much cleaner syntax if using rails 4+

<%= f.text_field :attr, placeholder: "placeholder text" %>

So rails 4+ can now use this syntax instead of the hash syntax

Solution 6 - Ruby on-Rails

In your view template, set a default value:

f.text_field :password, :value => "password"

In your Javascript (assuming jquery here):

$(document).ready(function() {
  //add a handler to remove the text
});

Solution 7 - Ruby on-Rails

This way works to me.

<%= form_for @product do |f| %>
<%= f.label :name %>
<%= f.text_field :name, placeholder: "Drill hammer" %>
<% end %>

As you can see, to implement a placeholder, you just can add the "placeholder: "text here", after your text_field name.

Hope my answer can be understood!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNullVoxPopuliView Question on Stackoverflow
Solution 1 - Ruby on-RailsnslocumView Answer on Stackoverflow
Solution 2 - Ruby on-RailsZoltanView Answer on Stackoverflow
Solution 3 - Ruby on-RailscwestonView Answer on Stackoverflow
Solution 4 - Ruby on-RailsProsper OparaView Answer on Stackoverflow
Solution 5 - Ruby on-RailsAbhilashView Answer on Stackoverflow
Solution 6 - Ruby on-RailsJed SchneiderView Answer on Stackoverflow
Solution 7 - Ruby on-RailsAntheaView Answer on Stackoverflow