Using JQuery to hide the value of text fields on focus

I created this little snippet (doesn’t really warrant a plugin) to remove the default value from a text field when the field receives focus. If for some reason the field loses focus the field will be refilled with the default value if you did not enter anything.

This is far from spectacular, I know but it’s a handy snippet that only requires you to add the swaptextbox to any input field (type of text) to enable it to work. You can have as many fields on a page that use this effect as you would like :)

Directions:

  1. Make sure you have JQuery running on your page
  2. Add the following code either to the page you wish the effect to affect or add it to a .js file
  3. Add the swaptextbox class to your input fields
var swap_text_boxes = [];

function init_swap_text_boxes(){
  //Store the default value for each box
  $('input[type=text][value].swaptextbox').each(function() {
    swap_text_boxes[$(this).attr('id')] = $(this).attr('value');
  });
  //Add focus and blur events to set or clear the value
  $('input[type=text][value].swaptextbox').bind('focus', function() {
    if($(this).val() == swap_text_boxes[$(this).attr('id')]) {
      $(this).val('');
    }
  });
  $('input[type=text][value].swaptextbox').bind('blur', function() {
    if($(this).val() == '') {
      $(this).val(swap_text_boxes[$(this).attr('id')]);
    }
  });
 }
$(document).ready(function(){ init_swap_text_boxes(); });