jQuery Plugin for using default value as label

Wrote a little plugin for using the default value in text elements as label, you know. Look at the right hand side in the newsletter form for an example.

[sourcecode language='javascript']
$.fn.label = function(options){

var default_settings = {
clearLabels : true
};

var settings = $.extend(default_settings, options);

return this.each(function(){
var elm = $(this);
if($(this).val().length > 0) {
$.data(elm, ‘default’, $(this).val());
elm.focus(function(){
if($(this).val() == $.data(elm, ‘default’)) {
$(this).val(”);
}
}).blur(function(){
if($(this).val() == ”) {
$(this).val($.data(elm, ‘default’));
}
});

if(settings.clearLabels) {
$(this.form).submit(function(){
if($(this).val() == $.data(elm, ‘default’)) {
$(this).val(”);
}
});
}
}
});
}
[/sourcecode]

Related posts

  1. jQuery, Thickbox and Google Analytics
  2. Unobtrusive Form Enhancements
  3. jQuery Form Validation Plugin
  4. JavaScript CSS Parser for Custom Properties
  5. jquery validation plugin checklist

3 thoughts on “jQuery Plugin for using default value as label

  1. Pingback: Unobtrusive Form Enhancements | Front-End Book

  2. Hi!

    There’s a bug in this in that the browser will sometimes auto-fill the fields. So you get the wrong default values. A more robust approach is putting the default values in the title attribute and sucking them from there.

    This is probably not a problem for your newsletter form, though, due to the way it’s being used.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>