Changing the default text value on focus with jQuery

Posted in Javascript -

You've seen those cool search boxes or login fields on websites which have some default value (like e.g. "Enter keywords here") and when you click into the field the default text disappears but is then restored if you click out of the box without typing anything. This post shows how to change the default value of an HTML text field on focus and blur with jQuery.

The best way to illustrate what I'm talking about is with an example. If you're viewing this in a RSS feed reader then you'll need to click through to this post in a web browser to be able to use the example below.

Play around with the example above by clicking one of the fields and then clicking out of it. You'll see the text go away and then come back again. If you click into the field, change the text and then click out again the new text you changed it to will stay there.

Here's the jQuery code which implements the above. Add this to your $(document).ready function:

$('.default-value').each(function() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = default_value;
        }
    });
});

Now all you need to do is add the "default-value" class to your <input type="text"> fields that you want this to work for. They don't even need to have an id attribute.

For example:

<input type="text" class="default-value" size="30" value="Enter keywords here" />
<input type="text" class="default-value" size="30" value="Another search box" />

And finally, you could also change the styles of the text box on focus and blur, as shown in the following code example which is a modification of the above. I've highlighted the modifications in red in the example below which makes the text a lighter color when it's showing the default text and a darker color when focussed.

$('.default-value').each(function() {
    var default_value = this.value;
    $(this).css('color', '#666'); // this could be in the style sheet instead
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
            $(this).css('color', '#333');
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            $(this).css('color', '#666');
            this.value = default_value;
        }
    });
});

And here's the second version working below:

Password fields

The next jQuery post will look at something similar, showing "Password" in plain text for a password field but changing to a proper password field with the password obscured on focus.

Full working example

I've followed these two posts up with a full working example which combines the two together, and has all the necessary source code all together.



Related posts:


Comments