Empty text boxes on focus if they have an initial value

josverhoeff 0 Tallied Votes 246 Views Share

Hi, I thought I'd share this with you. If you want all fields on a web form to be emptied of ther initial value (if any) on focus and filled again with the initial value on blur. Works with jquery.

$(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'));
		})
	});
JJenZz 36 Newbie Poster

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.

commented: Nice +6
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.