Rails Auto-Clearing Input Field

inputfieldAt certain times you might want to have a form input field have a description or default value that automatically clears when the user clicks the field to enter text.

An example of this is Digg’s search box. By default, it reads, “Search Digg…”, but when you click it, the default text disappears and makes room for your search terms.

To do this, we need to set the default value of the field using the value attribute, then set it to automatically clear when a user clicks it by using the onFocus event handler.

When a user clicks away from the field and the field is empty, we want to restore the default text. We can accomplish this with the onBlur event handler by checking whether the value is empty when the field loses focus. If it is, restore the default text.

Here is how you can implement this in HTML:

<input onFocus="if(this.value==this.defaultValue) this.value='';" onBlur="if(this.value=='') this.value=this.defaultValue;" type="text" value="Search..." />

Implementing this in Rails is just as easy. In your form code, use:

<%= text_field_tag(:s, "Search...", :onFocus => "if(this.value==this.defaultValue) this.value='';", :onBlur => "if(this.value=='') this.value=this.defaultValue;") %>

This is an example of such an input field: