Using jQuery to prepopulate inputs with default values, clear defaults onClick / focus

There are many ways to set and clear default form values using jQuery and javascript. Here's my preferred method. It doesn't cause any issues when javascript is disabled, and it allows you to set a different css class for empty vs non-empty inputs.

/* ** /* PREPOPULATE FIELDS */

//prepopulate fields that need default values (using rel attribute)
jQuery('.prepopulate').each(function(){
  jQuery(this).val( jQuery(this).attr('rel') );
});

//clear default value and add '.not-empty' class on click
jQuery('.prepopulate').focus( function(){
  if( jQuery(this).val() == jQuery(this).attr('rel') ){
    jQuery(this).val('').addClass('not-empty'); 
  }
});   

//restore default value & remove '.not-empty' class if left blank after click
jQuery('.prepopulate').blur(function(){
  if( jQuery(this).val() =='' ){
    jQuery(this).val( jQuery(this).attr('rel') ).removeClass('not-empty');
  }
});

/* **
/* END PREPOPULATE FIELDS
 */   

Now that you've added the jQuery, it's time to construct your form.

Just add the 'prepopulate' class and 'rel' attribute (containing your default) value.

Thanks for that - saved me some jQ Coding Time.
Any special reason why you dont use the short $(jquery) syntax?

At the time, I was avoiding namespace collisions. It shouldn't make any difference.

Hiiiiiiiiiiiiii

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.