HOWTO: Automatically Clear/Restore Form Defaults w/jQuery

11

May 13, 2008 - 4:21am

Just wanted to post this quick trick I've been using lately to automagically hide/show useful default text field values (e.g. "Search" in the search box) using jQuery and the ultra-handy Drupal.settings() object. Here's the short and sweet copy/pastable jQuery code:

 
$(document).ready(function(){   
  Drupal.settings.inputDefaults = {}   
  $("input:text").focus(function() {     
    var element = $(this);     
    Drupal.settings.inputDefaults[element.attr("id")] = element.val();     
    element.val('');   
  });   
  $("input:text").blur(function() {     
    var element = $(this);     
    if (element.val() == '') {
      element.val(Drupal.settings.inputDefaults[element.attr("id")]);
    }
  }); 
}); 

Basically this quick snippit will add a blank array object (ahh, the joys of moving between js and PHP) to the Drupal.settings object -- which is useful for all sorts of great javascript functionality, and is integral to Drupal 6.0's extended AHAH features; if you don't already know it, do your self a favor and study up -- and automatically fill it with any textarea's default values when a user clicks/tabs it into focus. This lets us clear the default value, but replace it quickly if the user moves on to another element.

As listed, you probably don't want this on your site, as it will affect things like editing nodes (e.g. title inputs will go blank when you click on them... not what you necessarily want), but it's easy to tune this to only hit elments within certain forms since every form in Drupal has a unique #id.

Thinking about this, I decided to tune it up and actually make an extended jQuery function for this so it could be more easily applied to speecific elements like so:

 
$(document).ready(function(){
   // handle hide/show for text field default values in only one form
   Drupal.settings.inputDefaults = {};
     $("#specific-form input:text").clearDefaultText();
   });
   jQuery.fn.clearDefaultText = function() {
     return this.each(function(){
       var element = $(this);
       Drupal.settings.inputDefaults[element.attr("id")] = element.val();
       element.focus(function() {
         if (element.val() == Drupal.settings.inputDefaults[element.attr("id")]) {
           element.val('');
         }
       });
     element.blur(function() {
       if (element.val() == '') {
         element.val(Drupal.settings.inputDefaults[element.attr("id")]);
       }
     });
   });
 } 

This is a pretty nice little plugin, I think, and it shows just how easy it can be to add nice/reusable UI functionality. Happy Drupaling, and go get 'em jQuery! (updated w/slight improvement to jQuery fn) (updated again w/object style improvements from comments)

Comments

Hi, thanks for the code. There was one problem, however. You use both 'input_defaults' and 'inputDefaults'. Thanks tho..really did help.

-Timothy

Fixed :)

Thanks, this is great. I could only get it to work for textboxes and not text areas, how would I fix this?

To get a text area to work, simply add ...

$("#specific-form textarea").clearDefaultText();

... right below ...

$("#specific-form input:text").clearDefaultText();

Enjoy,

Jason Bessonette

I cleaned your code up a bit for a strict use of jQuery. This is all you need. I appreciate the post!

$("input:text").focus(function()

var element = $(this);

element.attr("rel",element.val());

element.val('');

);

$("input:text").blur(function()

var element = $(this);

if (element.val() == '')

element.val(element.attr("rel"));

);

Hi,

Quick question- 1) Why you have used "rel" attribute in an "input" tag in a form, is it valid?

2)I'm unable to restore default value using same code.

Thinking about this, I decided to tune it up and actually make an extended jQuery function for this so it could be more easily applied to speecific elements like so:

The code works like a charm. Thanks.

I tried using the above code with a new D7 install, and quickly found that you must alter your document.ready statement in D7, yes?

(function ($)

// Original JavaScript code.

)(jQuery);

see http://drupal.org/update/modules/6/7#javascript_compatibility

I've corrected this, but still haven't gotten the script to clear default values. Has anyone gotten this to work in D7?

thanks

Thanks for sharing this post, very helpful to me

If you are like millions of Americans today, your weekly, bi-weekly or monthly paycheck from your employer gets direct-deposited into your checking account each month. If your regular direct deposit payment is taking a long time to clear, read on.

Great code sample - but I am running into an issue. It works when I am logged on but for visitors (not logged in) it does not work even though I can see that the javascript code is in the page source.

I log back in and it works: Log out, it stops working.....

To try this out on a form, I had simply imbedded the script into the drupal node's body tag with PHP code input format setting. To be clear, the script does not have php tags around it. Other scripts are working for Visitors so its not that they can't execute the script, it just seems that even with the script there in the page source, it does not work.

Post a comment

To prevent automated spam submissions leave this field empty.
CAPTCHA
Let us know you're human by typing in this code. The code is case sensitive.
Image CAPTCHA
Enter the characters shown in the image.