Feb 16

A jQuery Plugin: Default Values for Input Fields

One of the best ways to write code that you tend to have to re-use is to put it in the public domain. That way when you need it again, it's a Google search away from your own blog.

This is a rather simple working example of default text on an input field. Click on the field, the text disappears, only to reappear if the user clicks somewhere else on the page without typing. The input also has a special class signifying that it is empty, so you can style the empty input.

Demo

JavaScript Code

(function($) { $.fn.extend({ input_default: function(default_text, opts) { if (typeof default_text !== 'string') { opts = default_text; } else if (!opts) { opts = { 'default_text': default_text }; } else { $.extend(opts, {'default_text': default_text}); } var defaults = { 'default_text': 'Type here...', 'class_name': 'empty-input' }; var options = $.extend({}, defaults, opts); return this.each(function () { var $this = $(this); if ($this.val() == '' || $this.val() == options['default_text']) { $this.addClass(options['class_name']) .val(options['default_text']); } $this.bind('focus', function() { if ($this.val() == options['default_text']) { $this.val('') .removeClass(options['class_name']); } else { $this.select(); } }).bind('blur', function() { if ($.trim($this.val()) == '') { $this.val(options['default_text']) .addClass(options['class_name']); } else { $this.removeClass(options['class_name']); } }); }); } }); })(jQuery);

Usage

First, the HTML you can use: You can call `input_default` with no arguments and get the defaults: $('.text').input_default(); Specify an optional string or class: $('.text').input_default('Enter text here...', {'class_name': 'empty'}); Here is some sample CSS to use: .default-text { border: 1px solid #C0C0C0; padding: 2px; font-weight: bold; font-size: 14px; } .empty-input { color: #A0A0A0; } .default-text-label { font-size: 16px; font-weight: bold; color: #303030; }

Samuel Clay is a software engineer living in Brooklyn working on DocumentCloud, an open-source repository of primary source documents contributed by journalists, and NewsBlur, a feed reader with artificial intelligence.

His latest project is New York Field Guide, a photo-blog documenting New York City's 90 historic districts. You can read about his past and present projects at samuelclay.com.

Follow @samuelclay on Twitter.

You can email Samuel Clay at samuel@ofbrooklyn.com. He loves receiving email from new people. Who doesn't?

Elsewhere