Clear default value

I found many examples, but I'm trying to figure out the simplest way to clear the default input value on click.

This is for the search box. I have a "Message Search" and I want to clear it by clicking on it.

I tried using jquery but for some reason it does not 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 simpler code?

+3
source share
3 answers

It would be interesting to try this with the html5 attribute placeholder. This will work in all current versions of Safari, Chrome and Firefox.

<input type="text" name="s" id="search" placeholder="Search for post"/>

Then you need to add backup code for browsers that do not 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'));
                }
            });
    });
});

jsfiddle, . , , , , , , IE 6.

http://jsfiddle.net/V2R9J/ (: trim , . .)

: , ajax. - live, . , password, * - , .

, , , , , html5, , .

+2
+1

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

Source: https://habr.com/ru/post/1771601/


All Articles