Skip to content

Instantly share code, notes, and snippets.

@dragunoff
Created January 30, 2012 16:55
Show Gist options
  • Save dragunoff/1705408 to your computer and use it in GitHub Desktop.
Save dragunoff/1705408 to your computer and use it in GitHub Desktop.
[JS] Labels to text fields values
/*!
* Labels to text field values
* ===========================
*
* Set the default value of text fields to the text in a corresponding <label> element
*/
;(function($) {
$.fn.labelToValue = function() {
$(this).each(function() {
// vars
var $field = $(this),
$value = $field.val(),
$label = $field.prev(),
$labelText = $field.prev().text();
// do stuff
if ($value == '') {
$field.val($labelText);
}
$label.hide();
// binds
$field.bind({
focus: function() {
if ($field.val() == $labelText) {
$field.val('');
}
},
blur: function() {
if ($field.val() == '') {
$field.val($labelText);
}
}
});
});
return this;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment