Jquery code to empty form field on focus and populate form field on blur with field label

Clear the field values of a form on focus and populate the field with the title on blur. Thus if the field content is “First Name” and you click in the field the field will clear and if the field is clear and you click away from the field the content of the field will return to “First Name”.


Firstly we place the form into the page

<form action="#" method="" id="formfieldtest">
<input type="text" name="firstname" title="First Name" value="First Name">
</form>

Then in the header we specify the form field and set the Jquery focus function to check the contents of the field and match it against the title attribute of the field.

$("#formfieldtest input[type='text']").focus(function(){
  //retrieve the name of the field from the title attribute
  var fieldname = $(this).attr("title");
  //check if field is equal to the title, if so empty the field
	if($(this).val() == fieldname){
		$(this).val("");
	}//end if
});

Now we add in a blur function so that if the user clicks away from the field and the field is empty it populates the field with content of the title attribute of the field.

.blur(function(){
	//retrieve the name of the field from the title attribute
	var fieldname = $(this).attr("title");

	//check if field is empty, if so replace the field content with the title attribute value
		if($(this).val() == ""){
			$(this).val(fieldname);
		}//end if		
});

The complete script is below, simply copy and paste this into your page header, remember to make sure that the Jquery library is included into your page header as well.

<script type="text/javascript">
$(document).ready(function() {
  $("#formfieldtest input[type='text']").focus(function(){
	//retrieve the name of the field from the title
	var fieldname = $(this).attr("title");
	//check if field is equal to the title, if so replace the field content with nothing
	if($(this).val() == fieldname){
		$(this).val("");
	}//end if
   }).blur(function(){
	//retrieve the name of the field from the title
	var fieldname = $(this).attr("title");
	//check if field is empty, if so replace the field content with the title value
	if($(this).val() == ""){
		$(this).val(fieldname);
	}//end if		
   });
});
</script>

Hope this helps, Nathaniel.

%d bloggers like this: