How to add a placeholder to a text_field_tag?

2019-08-15 04:47发布

问题:

I have the following line in my form:

= text_field_tag :mother_name, nil, id: 'mother_name_autocomplete', class: 'form-group form-control', autocomplete: 'off', data: {provide: 'typeahead'}

How can I add a placehodler to this field?

回答1:

if you are using text_field_tag then you can do something like this.

<%= text_field_tag :mother_name, nil, placeholder: 'Some text' %>

notice that second argument is nil.



回答2:

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

f.text_field :mother_name, :placeholder => "mother_name_autocomplete"

You can find more reference here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html



回答3:

For Example, id = "input_name", value = nil, placeholder = "Enter your name"

So the tag is provided as,

 <%= text_field_tag 'input_name', nil, placeholder: "Enter your name" %>

The above code will be generated as mentioned below,

<input type="text" name="input_name" id="input_name" placeholder="Enter your name">

Read more about the tags here : https://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html



回答4:

<%= text_field_tag "search", 'Enter search term...' %>

Add an onclick event to empty it with jQuery:

<%= text_field_tag "search", 'Enter search term...', :onclick => 'if($(this).val()=="Enter search term..."){$(this).val("");};' %>

Reference:- Text Field Tag Placeholder Returning As Value