How to make default form values in jQuery

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to make default form values in jQuery

Post by Neo » Mon Mar 01, 2010 1:23 am

Here's a useful jQuery snippet that clears the default values of form fields on focus and refills them if no text is entered. It uses the attribute called defaultValue which stores the original value of a form field.

Code: Select all

$(document).ready(function() {
   $('input[type=text]').focus(function() {
      if($(this).val() == $(this).attr('defaultValue')) {
         $(this).val('');
      }
   })
   .blur(function() {
      if($(this).val().length == 0) {
         $(this).val($(this).attr('defaultValue'));
      }
   });
}); 
For example, assume you have a field like this:

Code: Select all

<input type="text" value="Search..." /> 
When the page loads, the text field will have "Search..." filled in. When you focus on it, this text will disappear (assuming it hasn't already been edited by you). When you leave focus without typing anything, the text will reappear.
Post Reply

Return to “Web programming”