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?
-
HTML5 Supports this. In the meantime, there are javascript solutions.– ghoppeJul 15, 2010 at 19:33
-
3I suggest adding nslocum's answer instead of mine. His is correct for Rails 3.– Chuck CallebsJan 24, 2012 at 3:09
7 Answers
With rails >= 3.0, you can simply use the placeholder
option.
f.text_field :attr, placeholder: "placeholder text"
-
4The "placeholder" attribute is only supported by HTML5 supporting browsers, leaving out browsers like Internet Explorer. Aug 8, 2011 at 20:52
-
1
-
1@KDP: It seems to be the same in Rails 2, although you may need the old attribute syntax:
f.text_field :attr, :placeholder => "placeholder text"
Nov 18, 2016 at 11:01 -
Is it possible to add a long text - maybe as a separate html file - as a placeholder? I'm trying to provide a template for users to write their content in. Jul 11, 2017 at 8:44
In Rails 4(Using HAML):
=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
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"
-
Thanks that worked. I didn't set the
placeholder: true
. After setting that like you described it worked.– HendrikNov 28, 2016 at 12:38
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"
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
-
1
-
@mlt The accepted answer got updated to similar after providing this answer.– AbhilashJul 15, 2018 at 16:05
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
});
-
1Huffington Post's search field uses this bit of JS inside the input element:
onfocus="if(this.value=='Search The Huffington Post')this.value=''" value="Search The Huffington Post"
Seems like a good approach.– NathanApr 8, 2012 at 0:40
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!