开发者

clear default value

I found a lot of 开发者_如何学JAVAexamples 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.

http://jsfiddle.net/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.


For an input, you want to use .focus()

Live demo: http://jsfiddle.net/rchern/aWdgZ/



$('#search').focus(function() {           
 $(this).val('');
 $(this).unbind('focus');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜