Archive for April, 2009

Auto-hide field prompt

Monday, April 6th, 2009

Recently I’ve developed a couple of forms that prompt user input via the value of the field rather than a label. For instance, the text “Enter your name” within a field that requires you to enter your name.

Usually I want the text to disappear when the user focuses on the input or textarea element and reappear if the user moves away from the the element without inputting any text.

This function looks for all input and textarea elements with the class “hide-prompt”. Simply run this function after the DOM has loaded. Make sure that your input and textarea elements have unique ID’s.

jQuery

function _field_value_prompt(){
	var field_list = $('input.hide-prompt, textarea.hide-prompt');
	var field_list_values = Array();
	for(var f=0; f < field_list.length;f++){
		field_list_values[$(current_element).attr('id')] = $(current_element).val();
	}
 
	$(field_list).focus(function(){
		if($(this).val() == field_list_values[$(this).attr('id')]){
			$(this).val('');
		}
	});
 
	$(field_list).blur(function(){
		if($(this).val() == ''){
			$(this).val(field_list_values[$(this).attr('id')]);
		}
	});
}

© 2006 - 2010 Matt Lowden. Creative Commons all rights reserved.