Ruby on Rails:如何将占位符文本添加到 f.text_field?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3259234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby on Rails: How do I add placeholder text to a f.text_field?
提问by NullVoxPopuli
How can I add placeholdertext to my f.text_fieldfields 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?
如何将placeholder文本添加到我的f.text_field字段,以便默认情况下预先编写文本,并且当用户在字段内单击时,文本消失 - 允许用户输入新文本?
回答by nslocum
With rails >= 3.0, you can simply use the placeholderoption.
如果 rails >= 3.0,您可以简单地使用该placeholder选项。
f.text_field :attr, placeholder: "placeholder text"
回答by Zoltan
In Rails 4(Using HAML):
在 Rails 4(使用 HAML)中:
=f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
回答by cweston
For those using Rails(4.2) Internationalization (I18n):
对于那些使用 Rails(4.2) 国际化 (I18n) 的人:
Set the placeholder attribute to true:
将占位符属性设置为 true:
f.text_field :attr, placeholder: true
and in your local file (ie. en.yml):
并在您的本地文件(即 en.yml)中:
en:
helpers:
placeholder:
model_name:
attr: "some placeholder text"
回答by Prosper Opara
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:
我尝试了上面的解决方案,它看起来像在 rails 5.* 上,默认情况下第二个参数是输入表单的值,对我有用的是:
text_field_tag :attr, "", placeholder: "placeholder text"
回答by Abhilash
Here is a much cleaner syntax if using rails 4+
如果使用,这是一个更清晰的语法 rails 4+
<%= f.text_field :attr, placeholder: "placeholder text" %>
So rails 4+can now use this syntax instead of the hash syntax
所以rails 4+现在可以使用这个语法而不是散列语法
回答by Jed Schneider
In your view template, set a default value:
在您的视图模板中,设置一个默认值:
f.text_field :password, :value => "password"
In your Javascript (assuming jquery here):
在您的 Javascript 中(假设这里是 jquery):
$(document).ready(function() {
//add a handler to remove the text
});

