Text Field Tag Placeholder Returning As Value

依然范特西╮ 提交于 2019-11-29 11:19:53

问题


I have a form and inside the form there is a text_field_tag. It is written as this...

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

However, when the HTML is generated this returns in the page source...

<input id="search" name="search" type="text" value="{:placeholder=&gt;&quot;Enter search 
term...&quot;}" />

Why is it doing this and how do I fix it so that placeholder works?


回答1:


The second parameter of the text_field_tag is the value. Give it nil to have it empty:

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

And give it a String to have a default value:

<%= 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("");};' %>

Edit 2016:

Nowadays, most of the browsers now support the HTML 5 placeholder, which allows us to do this in a cleaner way:

<%= text_field_tag 'search', nil, placeholder: 'Enter search term' %>
# which produces the following HTML:
<input type="text" value="" placeholder="Enter search term">

jsFiddle link



来源:https://stackoverflow.com/questions/13481986/text-field-tag-placeholder-returning-as-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!