Skip to content

Instantly share code, notes, and snippets.

@tkaemming
Created October 16, 2009 00:14
Show Gist options
  • Save tkaemming/211420 to your computer and use it in GitHub Desktop.
Save tkaemming/211420 to your computer and use it in GitHub Desktop.
(function ($) {
$.fn.defaultValue = function (defaultValue) {
return this.each(function (i) {
var currentField = $(this);
// Only apply the default value to text, password or textareas.
if (currentField.is(':not(input:text)') &&
currentField.is(':not(input:password)') &&
currentField.is(':not(textarea)')) {
return;
}
// Set the initial value if none is specified.
if (currentField.val() === '' || currentField.val() === defaultValue) {
currentField.val(defaultValue);
currentField.addClass('default');
} else {
return;
}
// Set the value to blank on focus.
currentField.bind('focus', function (event) {
if (currentField.val() === defaultValue) {
currentField.val('');
currentField.removeClass('default');
}
});
// Return the value to default on blur.
currentField.bind('blur', function (event) {
if (currentField.val() === '' || currentField.val() === defaultValue) {
currentField.val(defaultValue);
currentField.addClass('default');
}
});
// If the field is still the default value on submit, set it to blank.
currentField.closest('form').bind('submit', function (event) {
if (currentField.val() === defaultValue) {
currentField.val('');
currentField.removeClass('default');
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment