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

前端 未结 6 1279
囚心锁ツ
囚心锁ツ 2021-01-29 21:57

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 te

相关标签:
6条回答
  • 2021-01-29 22:14

    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"
    
    0 讨论(0)
  • 2021-01-29 22:24

    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"
    
    0 讨论(0)
  • 2021-01-29 22:25

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

    f.text_field :attr, placeholder: "placeholder text"
    
    0 讨论(0)
  • 2021-01-29 22:29

    In Rails 4(Using HAML):

    =f.text_field :first_name, class: 'form-control', autofocus: true, placeholder: 'First Name'
    
    0 讨论(0)
  • 2021-01-29 22:30

    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

    0 讨论(0)
  • 2021-01-29 22:34

    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
    });
    
    0 讨论(0)
提交回复
热议问题