Clear form fields on focus

If you want to make a form without labels for text inputs or textareas, and instead give the fields default values, you will encounter a little annoying  problem, when you focus the field to write something the default value stays there. To make the default value disappear you will need a few lines of javascript.

$('textarea, input:text').bind('focus click', function(){
		if (this.value == this.defaultValue) {
		this.value = '';
	}).bind('blur', function(){
		if (this.value == '') {
		this.value = this.defaultValue;

Note that this script uses jQuery so in order to work you’ll need to have jQuery installed.

To make all clear here is a demo.


  1. written by: Mehigh on January 25, 2011 at 7:39 pm - Reply

    I suggest using the placeholder attribute from HTML5 for storing the default value.
    It would be preferred to initially check if the placeholder attribute has built-in browser support, and only if it’s not available to run the few lines of script to enable this behavior.

    In 2011 all we need is to be semantic ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

79 − 74 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.