Skip to content Skip to sidebar Skip to footer

Clear Default Value

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

Solution 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.

<inputtype="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.

Solution 2:

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

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

Solution 3:


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

Post a Comment for "Clear Default Value"