jQuery: required form fields plugin

Surfing GitHub today I found a simple but interesting jQuery plugin that adds a background image to the required fields of a web form. It works fine, but it poses some problems. First of all, if you use only a background image, then screen reader users won't be able to tell the difference between a required and a non required field because they can't see the image. Second, this plugin adds a CSS class directly in the HTML and this is surely something that can be automated. So I created an ever simpler plugin that simply inserts the following HTML fragment on the parent element of a required field:

<element class="className">marker</element>

where element is the wrapper element, className is the CSS class to be attached to the wrapper and marker is a simple text character used to mark up a required field (e.g. with an asterisk). Now let's write our plugin code:

(function($) {

  $.fn.requiredFields = function(options) {
  
    options = options || {};
    options.wrapper = options.wrapper || 'span';
    options.cssClass = options.cssClass || 'required';
    options.marker = options.marker || '*';
    options.inputs = options.inputs || [];
    
    var self = this;
    
    if(self[0].tagName.toLowerCase() != 'form') {
    
      throw new Error('requiredFields() needs a form element to work.');
      
      return;
    
    }
    
    var element = '<' + options.wrapper + ' class="' + 
    options.cssClass + '">' + options.marker + 
    '</' + options.wrapper + '>';
    
    var i, len = options.inputs.length;
    
    for(i = 0; i < len; i += 1) {
    
      var input = options.inputs[i];
      
      var elem = self.find(input);
      
      var parent = elem.parent();
      
      $(element).appendTo(parent);
    
    }
    
    return self;
    
  
  };

})(jQuery);

This plugin is called requiredFields() and can be used only on HTML forms (we also added an internal check to make sure that it will be called on forms and forms only). It accepts four options:

requiredFields() options
Option Description
wrapper The wrapper HTML element used to contain our field marker. Defaults to span
cssClass The CSS class to be attached to the wrapper element. Defaults to required
marker The character text used as a marker. Defaults to an asterisk (*).
inputs An array of references to the input fields you want to mark as required. Without this option, this plugin won't work.

Let's see an example. We first set our CSS class:

span.required {
 float: left;
 width: 27px;
 height: 25px;
 background: url(field-marker.png) no-repeat;
 text-indent: -1000em;
}

Then we can use our plugin:

$(document).ready(function() {

$('#test').requiredFields({
  inputs: ['#email', '#openid']
});


});

You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: required form fields plugin”

Leave a Reply

Note: Only a member of this blog may post a comment.