Enterprise Drupal: Form Default Values

Nov 09, 2011
Francisco Alvarez

Enterprise Drupal: Webforms, JQuery and Default field values

Almost every website has a Webform, these are used for searches, profile managing or sending emails... We are going to explain an easy way to place a help (default) text on the Form's input fields, using jquery, with a behavior that doesn't interfeer with the desired funcionality for that Webform. On my case I implemented this solution on a Drupal project I was working on, so I'll just add a few notes about this, but the solution can be used everywhere.

The idea is to have a default text (normally with a lighter color) that disappears on focus and appears again onblur if the field is empty.

Below we have an example for you to try:

If you liked it, here's the code:

/*** Notice the class on the input ***/


/*** This is all the html you need ***/


<input class="default-value" type="text" value="Your text here..." />

/*** You can copy this script to your main js file***/


<script type="text/javascript">

/*** The following variables may be adjusted***/


var active_color = '#000'; // Color of user provided text
var inactive_color = '#ccc'; // Color of default text

$(document).ready(function() {
  $("input.default-value").css("color", inactive_color);
  var default_values = new Array();
  $("input.default-value").focus(function() {
    if (!default_values[this.id]) {
      default_values[this.id] = this.value;
    }
    if (this.value == default_values[this.id]) {
      this.value = '';
      this.style.color = active_color;
    }
    $(this).blur(function() {
      if (this.value == '') {
        this.style.color = inactive_color;
        this.value = default_values[this.id];
      }
    });
  });
});
</script>

Sometimes on Drupal is not that easy to add a class to an input, so I'll explain a really simple way to achieve the desired effect.

  • Go to the page that contains the form (Site building > Pages)
  • Click on edit the page
  • Open the "Content" section
  • Find the content portion that contains your form
  • Click the upper right icon and select the "CSS properties" option
  • Set your own ID or Class
  • Modify your javascript and add this class/id to the selectors (eg: input.default-value, #my-id).


I found the original post at http://webdeveloper.beforeseven.com/jquery/default-text-field-value-disappears-focus, the author of the code is Rob Schmitt. There's also a "no jquery" version of it.