Removing Default Form Input Values on Click

Penned on .

For an alternative method, see A Better Method for Clearing Default Form Input Values


Another quick and dirty jQuery trick. I often find myself wanting to place form instructions ('enter name here' or what have you) using the value attribute. Forcing a user to manually delete this information isn't what I would call great usability. But, with a little bit of javascripting, removing and replacing defaults on click is a piece of cake:

$('input[type=text], textarea').each(function() { 
$(this).focus(function() {
  if($(this).val() == this.defaultValue)
  $(this).blur(function() {
    if($(this).val() == "")

Simple, right? Now, every time a user clicks a form input or textarea, it will remove the default value. On blur, if no new text was entered, the default value was replaced. If at anytime new data was inserted, it won't ever be removed or replaced but if ever on blur the input is empty, the default value is replaced. Enjoy!