jQuery Plugin: clearOnFocus

Posted on Sep 15, 2009 @ 6:22 PM

A jQuery plugin that clears form input values on the focus event, and replaces the form's value with it's value attribute if no input has been entered into the form. Licensed jointly under the GPL and MIT licenses.

This plugin should work with any version of jQuery that supports the data method, which was introduced in version 1.2.3. It has been tested with jQuery 1.2.3 and jQuery 1.3.2.

 

USAGE:

Requires jQuery to be loaded before the plugin. To use clearOnFocus, give the form elements you want cleared on focus the class clearOnFocus. After the DOM has loaded, call the plugin to act on the class clearOnFocus as follows: $('.clearOnFocus').clearOnFocus();

 

DEMO:

Click here for a demo of clearOnFocus.

 

DOWNLOAD:

jquery.clearonfocus.js

(function($) {
	$.fn.clearOnFocus = function() {
		
		function clearOnFocusFocus(event)
		{
			if($(this).val() == $(this).data('clearOnFocus'))
			{
				$(this).val('');
			}
		}
		
		function clearOnFocusBlur(event)
		{
			if($.trim($(this).val()) == '')
			{
				$(this).val($(this).data('clearOnFocus'));
			}
		}
		
		return this.each(function()
			{
				$(this).data('clearOnFocus', $(this).attr('value'));
				
				//	unbind any previous listeners
				$(this).unbind('focus', clearOnFocusFocus);
				$(this).unbind('blur', clearOnFocusBlur);
				
				//	bind listeners to the functions
				$(this).bind('focus', clearOnFocusFocus);
				$(this).bind('blur', clearOnFocusBlur);
			}
		);
	};
})(jQuery);

1 Comment

Click For New Security Code Please enter the security code: