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.


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);


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; }


9:11 p.m. on March 18th, 2010
1 Jason says...
For the record, this is going to be a feature of HTML5 forms, for browsers that support it. http://www.whatwg.org/specs/web-apps/current-work/multipa...

Comments are closed.

That's all the comments I'm taking for this post. Email me your thoughts: blog+comments@ofbrooklyn.com.

Samuel Clay is the founder of NewsBlur, a personal RSS news reader for web, iOS, and Android. He is also the founder of Turn Touch, beautiful control for your smart home.

He lives in San Francisco, California. In another life in New York, he worked at the New York Times on DocumentCloud, an open-source repository of primary source documents contributed by journalists.

You can read about his past and present projects at samuelclay.com.

Follow @samuelclay on Twitter.

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