Tutorials -

Clearing Default Field Values with jQuery

Kevin Flahaut By Kevin Flahaut Published November 6, 2009

A few people have asked about automatically clearing the default field values on focus. While that’s not a feature in the current version of Gravity Forms, It’s easy enough to accomplish with a little bit of jQuery goodness. This script will remove any default value from input fields and textareas on focus, and if you haven’t changed it, will restore it on blur.

You can add the script below to your header.php file if you want it to be available for all of your forms, or can create a new page template, associate it with the page the form is on and include the script there. Note: This snippet requires that the jQuery library is already loaded in your theme to function properly.

The Script

<script type="text/javascript">

jQuery(document).ready(function() {

	jQuery.fn.cleardefault = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};
jQuery(".clearit input, .clearit textarea").cleardefault();

});

</script>

Defining the Fields

Once you’ve included the script in your page, it’s easy to define which fields you want to clear. Simply open up the form in the Gravity Forms admin, navigate to the field you want to clear, click on the Advanced tab and add the CSS Class Name “clearit“. Save the form and you’re good to go.

Clearing Default Fields

That’s all there is to it. Of course, you could tweak the script and change the class name to suit your preference.

Something to Consider

Please be aware that if you’re using default values on fields you’ve defined as required, they will validate even if the user doesn’t not populate them or change their value. This is due to the fact that the default value will be submitted as the form field value if they are not changed by the user.