文本字段标记占位符作为值返回 [英] Text Field Tag Placeholder Returning As Value

查看:114
本文介绍了文本字段标记占位符作为值返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格,里面有一个text_field_tag。它被写为...

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...' %>

但是,当生成HTML时,会返回页面源代码...

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?

推荐答案

text_field_tag的第二个参数是值。

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...' %>

使用jQuery添加一个onclick事件以清空它:

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



编辑2016:



现在,大多数的浏览器现在支持 HTML 5 占位符 ,这使我们能够以一种更清晰的方式做到这一点:

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链接

这篇关于文本字段标记占位符作为值返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆