$(document).ready(function () {
		// saves the initial value of all text fields
		$(':text').each(function () {
			$(this).attr('initialvalue', $(this).val());
		}); 
		// on focus, empty the field if it has the initial value
		$(":text").focus(function () {
			if ( $(this).attr('initialvalue') == $(this).val() ) $(this).val('');

		})
		// on blur, do the reverse if the field is empty
		$(":text").blur(function () {
			if ($(this).val() == '') $(this).val($(this).attr('initialvalue'));
		})
	});
2
Contributors
1
Reply
32
Views
3 Years
Discussion Span
Last Post by JJenZz
1

This can be done more simply as follows (although some may find harder to understand):

$(document).ready(function () {
  $(':text').on('blur focus', function (e) {
    var values = ['', this.defaultValue],
        isFocus = (e.type === 'focus');

    if (this.value === values[isFocus*1]) {
      this.value = values[!isFocus*1];
    }
  });
});

I guess the main benefit here being that you don't need to do your initialvalue stuff since there is already a native defaultValue for this.

Votes + Comments
Nice
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.