Quick Tip: Using JavaScript’s defaultValue for form elements

January 27, 2011
blog author

Appno Blogger

Appnovation Coop

I often find myself hiding form labels in favor of pre-populating a text field with some value, usually the label itself. For example, a search box that pre-populates with “Search” or “Search this site...”. It’s trivial to setup, but it can become a cumbersome task customizing the code for every new site or form. This is where using JavaScript’s built-in defaultValue on form elements greatly simplifies the code and makes it possible to create a plugin to do all the heavy lifting. After setting a defaultValue, you can simply check each value against its default value on form submission and clear any values that haven’t been set by the user.

That way, if the text field still says “Search this site...”, the input will be cleared before the form is submitted. An example plugin has been included. The plugin itself is useful for setting custom text to be displayed in the textbox (or defaulting to the label) and setting up .focus and .blur event handlers that hide/show the default value depending on the users interaction. Note: In Drupal, all form elements are wrapped in a div with a class ‘form-item’ so I usually target the wrapper itself and .find(‘label’) and .find(‘.form-text’) to target the label and input field. Using the example plugin assumes this setup for forms. The HTML

The JS

	// The first line below uses the label as the default value whereas the 
	// second line uses custom text
	//$('form#demo .form-item').innerLabel();
	$('form#demo .form-item').innerLabel('Search this site...');

The jQuery.innerLabel.js Plugin

	$.fn.innerLabel = function( default_text ){
		var element = this;
		// prevent non-existant elements from being processed
		if( $(element).length <= 0 ) {
			// Hide the label
			// Set the 
			var text = (default_text) ? default_text : element.find('label').text().trim();
			// add a class to be able to target processed form items
			// set the default value for the input text
			$(element).find('input[type=text]')[0].defaultValue = text;
			// Add focus/blur event handlers
				.focus( function() {
					// when user clicks, remove the default text	
					if ($(this).val() == $(this)[0].defaultValue) {
				.blur( function() {
					// when user moves away from text, 
					// replace the text with default if input is empty
					if ($(this).val().trim() == '') {

Have another solution or improvements to the plugin? Feel free to share it in the comments.