Input Field Hints Plugin For JQuery

Tuesday January 6, 2009 Freebies Tutorials

While working on a site last year I needed to display a message in an input field that would disappear once the user clicked on the field. This is a very common technique you see around the web. I do not have a lot of experience with JavaScript, so, with permission I started poking around my webucating buddy, Jeff Brown's site, which uses the technique for the search bar. At that time I was also reading Learning jQuery from Packt publishing. Towards the end of the book it started talking about plugin creation. Great! I knew enough from working with other web languages that there is no need to repeat code when it could be done once with a plugin rather than ten times for each field. After a bit of working I came up with the following plugin:

//Plugin to add text to an input field that disappears on focus
jQuery.fn.inputFieldText = function(string) { 		
	this.each(function() {
		$(this).val(string);
		$(this).focus(function(){
			if ($(this).val() == string){
				$(this).val('');
			}
		});
		$(this).blur(function(){
			if ($(this).val() == '' ){
				$(this).val(string);
			}
		});	
	});
}

What this does is accepts a string as a parameter and places it inside of the input field you want to add the effect to. Here is what it looks like when the plugin is in use:

$('input[name=name]').inputFieldText('Your Name');
$('input[name=email]').inputFieldText('Your Email');

Notice that instead of calling each form by a class, and hence add additional markup to your html, you can simply select the field you want by using the @name= selector. This will select the field with the name that you want (read more about advanced selectors on the jQuery documentation page). I tried to do the same thing for textarea, but kept running into issues with different browsers not displaying the user inputted text properly after you clicked out of the field... I will revisit that in due time. For now, please enjoy the jQuery input field hints plugin.