Skip to content

Instantly share code, notes, and snippets.

Created March 10, 2012 10:14
Show Gist options
  • Save bfncs/2011030 to your computer and use it in GitHub Desktop.
Save bfncs/2011030 to your computer and use it in GitHub Desktop.
jQuery Plugin: Default form values from labels

jQuery Default Values

jQuery Plugin to set form input default values from labels

Author: Marc Loehe,


  1. Be sure to have your text inputs and textareas provided with labels correctly.

    <label for="mytextinput">Name of my text input</label>
    <input type="text" name="mytextinput" id="mytextinput" />
  2. Include jQuery in your page.

  3. Include the plugin in your page.

    Either load it separatly...

    <script type="text/javascript" src="js/jquery.defaultvalues.js"></script>

    ...or copy and paste it into some piece of code your using anyway.

  4. Call DefaultValues on a parent element of your inputs (preferably the <form>)after the DOM is loaded.

    $(document).ready(function() {
  5. You may want to provide a way to hide the now obsolete labels via css and js-detection.


2012-03-10 Initial release

/* DefaultValues v0.1 - Form input default values from labels
* by Marc Loehe
(function ($) {
$.fn.DefaultValues = function() {
return this.each(function() {
var form = $(this);
$(this).find('input[type=text], textarea').each(function() {
var el = $(this);
var id = el.attr('id');
var label = form.find('label[for=' + id + ']');
if (label.length > 0) {
var def = label.html();
el.val(def).focus(function() {
if(el.val() == def) el.val("");
}).blur(function() {
if(el.val() == "") el.val(def);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment