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. JavaScript CSS Parser for Custom Properties
  3. jQuery Form Validation Plugin
  4. Unobtrusive Form Enhancements
  5. jquery validation plugin checklist
This entry was posted in JavaScript and tagged , , , , . Bookmark the permalink.

3 Responses to jQuery Plugin for using default value as label

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

  2. Ole Laursen says:

    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.

  3. @Ole: Thanks for the input, I will update the script when I have the time.

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>