//

Here’s a little piece of jquery/javascript that I find myself using frequently. It’s not revolutionary - in fact I think I originally based it on somebody else’s code, but I think this is the only one that retrieves the hint text from the input's associated label. This means that it degrades really nicely, and encourages a good semantic form.


$.fn.hint = function () {
    return this.each(function () {
        var input = $(this);
        if (input.attr('type')!='text' && 
                   input[0].tagName != 'TEXTAREA'){
            return;
            }

        var form = $(this.form);

        var label = form.find('label[for=' +
                     $(this).attr('id') + ']');
        var text = label.text()
        label.hide();

        function remove() {
            if (input.val() === text && 
                              input.hasClass('blur')) {
                input.val('').removeClass('blur');
                  }
            }

        input.blur(function () {
            if (this.value === '') {
                input.addClass('blur').val(text);
            }
        }).focus(remove).blur();
        form.submit(remove);
          $(window).unload(remove); // handles Firefox's autocomplete
    });
};


And then to use it:

<label for =”to_hint”>Hint text</label>
<input type = 'text' id = “to_hint”></input>
...
$(“input#to_hint”).hint()

For example: