clear default value

2019-02-18 21:39发布

问题:

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?

回答1:

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.



回答2:

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

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



回答3:


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