这是用于搜索的。
我发现了很多示例,但我试图找出最简单的方法来清除输入的默认值。框。我有搜索帖子,我想清除它,当点击它。
我尝试使用jquery,但由于某种原因它不起作用。
$ b $ pre $ $('#search')。click(function(){ if($(this).val()= ='搜索帖子') $(this).val(''); }); < input type =textname =sid =searchvalue =搜索帖子>任何人都可以想到更简单的代码吗?
占位符属性来尝试使用它会很有趣。这可适用于所有当前版本的Safari,Chrome和Firefox。 < input type =textname = sid =searchplaceholder =搜索帖子/>然后,您需要为不支持此功能的浏览器添加一些后备代码。
$(function(){ $(':input [placeholder]')。each(function(){ var me = $(this); me.val(me.attr('placeholder')) .focus(function(){ var that = $(this); if(that.val()== that.attr('placeholder')){ that.val(''); } })。blur(function (){ var that = $(this); if(that.val()。trim()。length == 0){ that.val(that.attr(' placeholder')); } }); }); });我扔了一个jsfiddle来测试这个。对于那些支持它的人来说,它似乎很有效,而对于像IE 6这样的浏览器来说,它似乎很好。
jsfiddle/V2R9J/ (注意:我将 trim 更改为一个空字符串比较只是为了让它起作用,您可以/应该在这里使用您自己的修剪功能。)免责声明:这不起作用用于通过ajax插入的字段。你可以尝试一些实况,或者你可以手动调用一个方法。此外,它可以在 password 字段中工作,因为它只会让它们显示 * 或其他项目符号字段,但这已经是一个问题了。
这是相当实验性的,但它似乎是一个非常酷的解决方案,它允许使用较新浏览器的人获得一些非常棒的功能在html5中,虽然尽可能简单。
I found a lot of examples but I'm trying to figure out the simplest way to clear an input's default value when clicking it.
This is for a search box. I have "Search for post" and I want to clear that when clicking on it.
I tried using jquery but for some reason it doesn't work.
$('#search').click(function() { if($(this).val() == 'Search for post') $(this).val(''); }); <input type="text" name="s" id="search" value="Search for post">Can anyone think of a simpler code?
解决方案It would be interesting to try this with the html5 placeholder attribute. This would work on all current versions of Safari, Chrome, and Firefox.
<input type="text" name="s" id="search" placeholder="Search for post"/>You then need to add some fallback code for browsers that don't support this feature.
$(function() { $(':input[placeholder]').each(function() { var me = $(this); me.val(me.attr('placeholder')) .focus(function() { var that = $(this); if (that.val() == that.attr('placeholder')) { that.val(''); } }).blur(function() { var that = $(this); if (that.val().trim().length == 0) { that.val(that.attr('placeholder')); } }); }); });I threw together a jsfiddle to test this out. It seems to work great for those that support it, and other as good as it can be for browsers like IE 6.
jsfiddle/V2R9J/ (Note: I changed the trim to a empty string comparison just to get it to work. You could/should use your own trim function here instead.)
Disclaimer : This won't work for fields that are inserted via ajax. You could attempt something with live, or you could manually invoke a method. Also - it work work with password fields, since it will just make them show the * or some other bulleted field, but that was already a problem.
This is pretty experimental, but it seems like a really cool solution that allows people who use the newer browsers to get some of the awesome functionality in html5, albeit as simple as it is.
更多推荐
清除默认值
发布评论