Often times, in place of labels, designers will choose to put default text in a form field to denote the information that it should contain. This is good design and usability, but it also creates some functional problems. Obviously, the text should disappear when the field is in focus, but what happens if the user clicks away without entering anything, or submits the form before filling in the field?

This handy jQuery function solves those problems. Default text will appear in the field whenever it is empty and not in focus. The user can click it to remove the text, then click away to reveal it again. If the field has been filled out, nothing happens. As a bonus, if the form in question is submitted with default values, those are cleared before the submission takes place to allow for proper validation.


function default_text(selector, text){
  element = $(selector);
  if (element.val() == ''){
    element.val(text);
  }
  element.focus(function(){
    if ($(this).val() == text){
      $(this).val('');
    }
  }).blur(function(){
    if ($(this).val() == ''){
      $(this).val(text);
    }
  }).parents('form').submit(function(){
    if (element.val() == text){
      element.val('');
    }
  });
}

$(document).ready(function(){
  default_text('#your_form_element_id', 'Your default text');
});

One thought on “jQuery Default Form Text Function

Leave a Reply

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