Tag Archives: semantic web

Toggle Text Field Values with jQuery

UPDATED: Project moved to Git!

I saw this post on the CSS Tricks Snippet Feed which addresses a commonly desired form behavior: to provide default text in an INPUT element that disappears when the user enters that field. The example provided works, but I have a couple issues with it:

  1. Uses inline JavaScript, and must be reapplied to each element affected
  2. Repeats the contents of the value attribute
  3. The default text is not replaced if the user exits the field without entering new data

So I created a possible solution, using jQuery:

HTML

1
<input type="text" value="Place default text here" />

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
jQuery( function(){
  $( 'input[type="text"]' ).each( function(){
    $(this).attr( 'title', $(this).val() )
      .focus( function(){
        if ( $(this).val() == $(this).attr('title') ) {
          $(this).val( '' );
        }
      } ).blur( function(){
        if ( $(this).val() == '' || $(this).val() == ' ' ) {
          $(this).val( $(this).attr('title') );
        }
      } );
  } );
} );

This script first iterates over each of the text input to assign a semantic text attribute, helpful not only in storing the default value, but also providing a tool-tip for reference as the user interacts with the page. It then assigns behaviors for both the onfocus and onblur events, eliminating the need to respecify data for comparison. The script is cleanly separated from the markup and, using jQuery, additional specifications may be made so as to only affect children of a particular FIELDSET or only those that possess a certain class.

I hope you find this snippet useful, and feel free to comment if you have additional information to share.


UPDATED!

We, as designers and developers, cannot help but go back to review our sites and code to make updates and revisions as our skills, philosophies and tastes change. In this spirit, I would like to offer an alternative to the above JavaScript snippet. The one above, in my opinion, is lacking in the following ways:

  1. Applies the behavior to all input[type="text"] elements indiscriminantly.
  2. Overwrites any existing title attribute content
  3. Does not account for existing text field values resulting from pre-population or validation.

So with that in mind, here’s the new solution:

HTML

1
2
<input type="text" title="Place default assistive text here (e.g. First Name)" />
<input type="text" title="Default assistive text (e.g. E-Mail Address)" value="invalid@ddr.ess" />

jQuery Plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.fn.toggleField = function(){
  return this.each(function(){
    var $this = $(this);
    if($this.val() === '' && $this.attr('title') !== ''){
      $this.val($this.attr('title'));
    }
    $this.bind('focus blur', function(){
      var $this = $(this);
      if($this.val() === $this.attr('title')){
        $this.val('');
      }else if($this.val() === '' || $this.val() === ' '){
        $this.val($this.attr('title'));
      }
    });
  });
};

JavaScript

1
2
3
jQuery(document).ready(function(){
  $('input[type="text"]').toggleField();
});

By converting the behavior into a plugin, it becomes chainable and more flexible. Perhaps in a future version it would be useful accommodate additional field types or textarea elements. I have also packaged the plugin for download (zipToggleField jQuery Plugin). I look forward to seeing your questions or suggestions in the comments below!

Project Moved to Git

After further review and consideration, I decided to make some more changes to the plug-in to take advantage of some of the new features promoted in HTML5. Specifically the placeholder attribute, since this is essentially the behavior that we are trying to mimic. Here is an example:

<label for="email">Email:</label>
<input type="email" id="email" name="email" title="Enter a valid email address" placeholder="account@domain.tld"/>

The previous zip file will remain available above, but the toggleField.jquery.js project updates will progress on GitHub instead. Thanks to everyone for your suggestions and support!