JQuery – Search box with default text

Ever wanted to do a search box with a default text that automatically clears when clicked on ?

Here is the code for it :

JAVASCRIPT [Show Plain Code]:
  1. $("#src_txt").live("blur", function(){
  2.         var default_value = $(this).attr("rel");
  3.         if ($(this).val() == ""){
  4.                 $(this).val(default_value);
  5.         }
  6. }).live("focus", function(){
  7.         var default_value = $(this).attr("rel");
  8.         if ($(this).val() == default_value){
  9.                 $(this).val("");
  10.         }
  11. });

To make it work on your code you need to add an id property to the textbox you want it to work on and a rel property with the same value as the default value :

  1. <input type="text" value="Search …" rel="Search …" id="src_txt" />

And a demo of the code :

That was all 🙂 Enjoy!

One comment on “JQuery – Search box with default text

  1. Thanks! It’s a great simple feature. Going to use it on my app. I’ll be sure to get you credit.

Leave a Reply

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

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