2 * jQuery.labelify - Display in-textbox hints
3 * Stuart Langridge, http://www.kryogenix.org/
4 * Released into the public domain
6 * @author Stuart Langridge
10 * Basic calling syntax: $("input").labelify();
11 * Defaults to taking the in-field label from the field's title attribute
13 * You can also pass an options object with the following keys:
15 * "title" to get the in-field label from the field's title attribute
16 * (this is the default)
17 * "label" to get the in-field label from the inner text of the field's label
18 * (note that the label must be attached to the field with for="fieldid")
19 * a function which takes one parameter, the input field, and returns
20 * whatever text it likes
23 * a class that will be applied to the input field when it contains the
24 * label and removed when it contains user input. Defaults to blank.
27 jQuery.fn.labelify = function(settings) {
28 settings = jQuery.extend({
33 title: function(input) {
34 return $(input).attr("title");
36 label: function(input) {
37 return $("label[for=" + input.id +"]").text();
41 var jQuery_labellified_elements = $(this);
42 return $(this).each(function() {
43 if (typeof settings.text === "string") {
44 lookup = lookups[settings.text]; // what if not there?
46 lookup = settings.text; // what if not a fn?
48 // bail if lookup isn't a function or if it returns undefined
49 if (typeof lookup !== "function") { return; }
50 var lookupval = lookup(this);
51 if (!lookupval) { return; }
53 // need to strip newlines because the browser strips them
54 // if you set textbox.value to a string containing them
55 $(this).data("label",lookup(this).replace(/\n/g,''));
56 $(this).focus(function() {
57 if (this.value === $(this).data("label")) {
58 this.value = this.defaultValue;
59 $(this).removeClass(settings.labelledClass);
62 if (this.value === this.defaultValue) {
63 this.value = $(this).data("label");
64 $(this).addClass(settings.labelledClass);
68 var removeValuesOnExit = function() {
69 jQuery_labellified_elements.each(function(){
70 if (this.value === $(this).data("label")) {
71 this.value = this.defaultValue;
72 $(this).removeClass(settings.labelledClass);
77 $(this).parents("form").submit(removeValuesOnExit);
78 $(window).unload(removeValuesOnExit);
80 if (this.value !== this.defaultValue) {
81 // user already started typing; don't overwrite their work!
84 // actually set the value
85 this.value = $(this).data("label");
86 $(this).addClass(settings.labelledClass);