Entity view (Content)

Quick Tip: Using JavaScript’s defaultValue for form elements
By admin_1
Jan. 27, 2011

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

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

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

Post Tags: