Home

Warren J. Thompson

Intro

Hi everyone! This is my first jQuery plugin and my first open source project so go easy on me.

The project is called "awesomeForms" and it's basically a way to turn a really long, boring form into a multipage user experience with thumbnails for easy navigation, and integration of the jQuery validation plugin at http://bassistance.de/jquery-plugins/jquery-plugin-validation/ by JÖRN ZAEFFERER. The form validates itself as the user tabs through each input element, and also as they switch pages. Pages that don't pass validation are outlined in red, and pages that pass validation are turned green.

Getting started:

Well, the first step is to create the appropriate HTML structure for the form. Basically, a form with only one page would look something like this:

        <form id="awesomeForm" style="clear:both;">

                <fieldset>
                    <legend>Personal Information</legend>
                    <label for="dateOfArrival">Future Meeting Date</label>
                    <input type="text" id="dateOfArrival" name="dateOfArrival" class="required" />                        
                    <label for="accident">Have you recently been involved in an accident/injury?</label>
                    <div>
                    <input class="required" type="radio" name="accident" value="Yes" />Yes
                    <input type="radio" name="accident" value="No" />No
                    </div>
                    <label for="legalFirstName">Legal first name</label>
                    <input type="text" name="legalFirstName" class="required" />
                    <label for="legalMiddleName">Legal middle name</label>
                    <input type="text" name="legalMiddleName" />
                    <label for="legalLastName">Legal last name</label>
                    <input type="text" name="legalLastName" class="required" />

                </fieldset>

        </form>

1) The form itself has to be given the class of "awesomeForm".
2) Each page is separated by a fieldset tag, which is required
4) Legend tag labels the page
5) Each input control consists of a "label /input" pair. That IS absolutely necessary - every input needs to be in the format of label tag, and then input tag.
6) Radio button groups also need a special format. Again, this is necessary, and the script will break if the format changes. The radio input elements need to be grouped in a div that follows the label tag, like below:

                    <label for="accident">Have you recently been involved in an accident/injury?</label>
                    <div>
                    <input class="required" type="radio" name="accident" value="Yes" />Yes
                    <input type="radio" name="accident" value="No" />No
                    </div>

The second step is to include a copy of jQuery and the jQuery validate plugin.

jQuery: https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
jQuery validate: http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js

The plugin also works with many of the other plugins like jQuery mask or jQuery, so include those if desired. The validation plugin is mandatory.

Finally, initialize the plugin by calling it on the awesomePage class, like so:

$('#awesomeForm').awesomeForm();

Methods:

It currently comes with four methods:

hidePage: Hides a page from the stack of documents and the thumbnails page.
showPage: Shows a hidden page, and makes it appear back in it's appropriate location.
goToPage: Navigate directly to a page in the stack of pages.
validateForm: Calls the jQuery validate plugin to validate every element in the form.

hidePage/showPage

Hiding pages is zero based, so to hide page 2 of the form would look something like this:

$('#awesomeForm').awesomeForm('hidePage',1);

Where 1 is the page number, or the 2nd page starting from page 0.

to show the page again:

$('#awesomeForm').awesomeForm('showPage',1);

A more advanced example:

// A very simple hide/show page function.  
// If the accident radio button is checked, show that form.  
// Otherwise, hide it.  (It has to be rehidden in case
// people switch the box to yes, and then back to no.)
$("input:radio[name=accident]").change(function(){
    if ($("input:radio[name='accident']:checked").val() == 'Yes') {                         
        $('#awesomeForm').awesomeForm('showPage',9);
    }
    else {
        $('#awesomeForm').awesomeForm('hidePage',9);
    };              
});

goToPage

This takes you directly to the (zero-based) page number of the form, as in this example;

$('#awesomeForm').awesomeForm('goToPage',isReadyToSubmit);

validateForm

This validates every single input element in the form, and is usually called before submitting the form - although it can be called for any event.

$('#awesomeForm').awesomeForm('validateForm');

Examples:

Simple Hide/Show Page

$("input:radio[name=accident]").change(function(){
    if ($("input:radio[name='accident']:checked").val() == 'Yes') {                         
        $('#awesomeForm').awesomeForm('showPage',9);
    }
    else {
        $('#awesomeForm').awesomeForm('hidePage',9);
    };              
});

Custom Validation Message/Integration with jQuery validation plugin:

// Here is an example of some custom validation using the jQuery validation plugin
// from http://bassistance.de/jquery-plugins/jquery-plugin-validation/
// This calculates the birthday as soon as the user leaves focus
// and determines if the user is a minor or not.
$("#birthDate").focusout(function() {

        // This calculates if they are over 18 or not.
        var dateText = $("#birthDate").val();
        var currentDate = dateText.split("/");
        var day = currentDate[1];
        var month = currentDate[0];
        var year = currentDate[2];
        var age = 18;

        // My data is the birthday converted into a JavaScript object
        var mydate = new Date();
        mydate.setFullYear(year, month-1, day);

        var currdate = new Date();

        // If this is not a valid birthday (i.e. the baby is born in
        // the future.
        if (mydate > currdate) {
            $(this).val("");
            jQuery.validator.messages.required = "Whoa!  You were born in the future?!?";
            $("#awesomeForm").validate().element("#birthDate");
            jQuery.validator.messages.required = "This field is required.";
        }
        else {          
            // If they are a minor, add the two minor forms.
            // If not, remove the forms again.  (They have to 
            // be removed again, in case the user switches them
            // on and off.
            currdate.setFullYear(currdate.getFullYear() - age);
            if ((currdate - mydate) < 0){
                $('#awesomeForm').awesomeForm('showPage',2);
                $('#awesomeForm').awesomeForm('showPage',6);
            }
            else {
                $('#awesomeForm').awesomeForm('hidePage',2);
                $('#awesomeForm').awesomeForm('hidePage',6);
            }
        }
});

Form submission

//  This is where the form finally submits, to a file called confirm.php
//  Before submitting, the form is validated.  If it doesn't validate - then
//  it goes the page with validation errors.
$('#awesomeForm').submit(function() {
    // Validate the form
    isReadyToSubmit = $('#awesomeForm').awesomeForm('validateForm');
    // If it validates then seralize all the inputs and post them
    // to the server side processing page.
    if (isReadyToSubmit === true) {
        var urlstring = $(this).serialize();
        $.post('/confirm.php', urlstring, function(data) {
            $('#main-content').html(data);
        });
    } else {
        // Otherwise - go the page that has the error,
        // which was returned from the validation method above.
        $('#awesomeForm').awesomeForm('goToPage',isReadyToSubmit);
    };
    return false;       
});