Automatically empty a search box on focus with jQuery

Marc-Antoine Ross April 23rd, 2009

This simple Javascript snippet will bind the focus event to any element that has a “clearSearch” css class. On focus, the field is emptied if it is the default value. On blur, it will put back the default value if nothing was entered. Very simple and unobtrusive. You can use it on your registration forms as well!

TAXI.clearField = function() {
    $(’.clearSearch’).bind(’focus’, function(){
        if( this.value == this.defaultValue ) {
            this.value = ”";
        }
    });
    $(’.clearSearch’).bind(’blur’, function(){
        if( !this.value.length ) {
            this.value = this.defaultValue;
        }
    });
};

Entry Filed under: JavaScript

Leave a Comment

Required

Required, hidden

Some HTML allowed

Trackback this post  |  Subscribe to the comments via RSS Feed

Schedule

April 2009
M T W T F S S
« Mar   Aug »
 12345
6789101112
13141516171819
20212223242526
27282930