Building a jQuery Step-by-Step Form

 

Introduction

A couple weeks ago I was asked to build a long form for accepting camp applications. I know as well as you do how annoying and tedious web forms can get. One thing that I believe enhances a form’s usability is breaking it up into chunks. It is the same concept as breaking up content by using headings as it prevents the visitor from being too overwhelmed and eventually giving up.

I have developed a nice way to give the user a step-by-step form by using jQuery. Let us jump into it below!

Demo

By popular request I have added the demo. View It here!

The HTML

Open a blank HTML file and paste the following in:

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>jQuery Step-by-Step Form | Brenelz Web Solutions</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
</head>

<body>

<h1>Camper Application Form</h1>

<p>Please use this online application form to register for camp.</p>
<form id="camperapplicationForm"method="post" action="">

<div id="first-step">
	<h2>First Step</h2>
	<div>
		<div class="label"><label for="Gender">Gender</label></div>
		<select name="Gender" id="Gender">
			<option value="" selected="selected"></option>
			<option value="Male">Male</option>

			<option value="Female">Female</option>
	    </select>
	</div>

	<div>
		<div class="label"><label for="Grade">Grade in Fall 2009</label></div>
		<select name="Grade" id="Grade">
			<option value="" selected="selected"></option>
			<option value="K">K</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
			<option value="10">10</option>
			<option value="11">11</option>
			<option value="12">12</option>
	    </select>
	</div>
</div>


<div id="second-step">
	<h2>Second Step</h2>
    <div class="label"><label for="Site">Site</label></div>
    <select name="Site" id="Site">

        <option value="" selected="selected"></option>
        <option value="Cross-View">Cross View (Main Site)</option>
        <option value="Teepee-Village">Teepee Village</option>
        <option value="Mission-Point">Mission Point</option>
    </select>
</div> <!-- end second-step -->

<div id="last-step">
	<h2>Last Step</h2>
	<p>Please select one of the following payment methods.</p>
	<div>
	    <input type="radio" name="payment" id="payment0" value="Credit Card" /><label>Credit Card</label>
	</div>
	<div>
	    <input type="radio" name="payment" id="payment1" value="Cheque" /><label>Cheque</label>
	</div>

	<input type="submit" name="submit" id="submit" value="submit" />
</div> <!-- end last-step -->


</form>
</body>
</html>

Above we have created a short form with 3 steps, which in reality could have many more. The one real important thing to note is that each “step” is wrapped in a <div> with an id. For our example to work, we need to make sure this div is a direct child of the <form> element.

We will hide/show these <div>’s depending on where we are in the signing up process. You may be wondering how we are going to move between the different steps. I have purposely left this out of the HTML, because really we only want those links to show up when JavaScript is enabled. When JavaScript is disabled our whole form will show, and thus do not need the next/previous links. This is termed progressive enhancement in the JavaScript world.

Now onto the jQuery magic!

The jQuery

Setup
// when the dom is ready to be manipulated
$(function(){

    // remember our divs are direct childs of our form
    $('#camperapplicationForm > div')
        .hide();

    // don't forget to show the first step when page is loaded!
    $('#first-step').show();
});

All we are doing here is hiding all the divs by default and enabling the first one as soon as the page loads.

Next/Previous buttons

Creating the next/previous buttons is really the hardest functionality to code. Let’s create a variable to hold our HTML:

		var prevLink = '<a class="prev" href="#">< < Prev</a>';
		var nextLink = '</a><a class="next" href="#">Next >></a>';
		var navHTML = '<div class="prev-next">' +
					  	 prevLink +
						 nextLink +
			             '</div>';

This has not yet put the code into our document… so let’s append the above HTML to every step:

$('#camperapplicationForm > div')
	.hide()
	.append(navHTML);

Now the above will show the next and previous button on every step, but we want to disable the appropriate button when we are on the first or last step. Add the below:

$('#first-step .prev').remove();
$('#last-step .next').remove();

Now we need to code the actual functionality of the buttons:

$('a.next').click(function(){
	$(this).parent().parent().hide().next().show();
});

$('a.prev').click(function(){
	$(this).parent().parent().hide().prev().show();
});

This might seem weird having parent() so often but this is how it breaks down for the previous button:

<form>
     <!-- ($this).parent().parent().prev(); -->
    <div id="second-step">
    </div>

    <!-- ($this).parent().parent() -->
    <div id="last-step">

        <!-- $(this).parent() -->
       <div id="prev-next">

            <!-- $(this) -->
           <a class="prev" href="#">Previous</a>
       </div> <!-- end prev-next -->
    </div> <!-- end last-step -->
</form>

From the above we see we are hiding the current step (Eg. last-step) and showing the previous one (Eg. second-step)

How do we validate each step?

Now that we have our functionality pretty much complete, we turn to how we validate each step separately. Normally we would write some JavaScript to validate the entire form, but in this case that doesn’t work. Remember we only want to validate when the next button is clicked, but not the previous button. Change the “next” function to:


$('a.next').click(function(){
	var whichStep = $(this).parent().parent().attr('id');

	if( whichStep == 'first-step' )
	{
		// validate first-step
	}
	else if( whichStep == 'second-step' )
	{
		// validate second-step
	}
	else if( whichStep == 'last-step' )
	{
		// validate last-step
	}
	$(this).parent().parent().hide().next().show();
});

The Completed Source

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>TUT</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

    <script type="text/javascript">
		var prevLink = '<a class="prev" href="#">< < Prev</a>';
		var nextLink = '</a><a class="next" href="#">Next >></a>';
		var navHTML = '<div class="prev-next">' +
					  	 prevLink +
						 nextLink +
					  '</div>';
		$(function(){
			// init
			$('#camperapplicationForm > div')
				.hide()
				.append(navHTML);
			$('#first-step .prev').remove();
			$('#last-step .next').remove();

			// show first step
			$('#first-step').show();


			$('a.next').click(function(){
				var whichStep = $(this).parent().parent().attr('id');

				if( whichStep == 'first-step' )
				{
					// validate first-step
				}
				else if( whichStep == 'second-step' )
				{
					// validate second-step
				}
				else if( whichStep == 'last-step' )
				{
					// validate last-step
				}

				$(this).parent().parent().hide().next().show();
			});

			$('a.prev').click(function(){
				$(this).parent().parent().hide().prev().show();
			});
		});
	</script>
</head>

<body>

<h1>Camper Application Form</h1>

<p>Please use this online application form to register for camp.</p>
<form id="camperapplicationForm"method="post" action="">

<div id="first-step">
	<h2>First Step</h2>
	<div>
		<div class="label"><label for="Gender">Gender</label></div>
		<select name="Gender" id="Gender">
			<option value="" selected="selected"></option>
			<option value="Male">Male</option>

			<option value="Female">Female</option>
	    </select>
	</div>

	<div>
		<div class="label"><label for="Grade">Grade in Fall 2009</label></div>
		<select name="Grade" id="Grade">
			<option value="" selected="selected"></option>
			<option value="K">K</option>
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
			<option value="10">10</option>
			<option value="11">11</option>
			<option value="12">12</option>
	    </select>
	</div>


</div>


<div id="second-step">
	<h2>Second Step</h2>
    <div class="label"><label for="Site">Site</label></div>
    <select name="Site" id="Site">

        <option value="" selected="selected"></option>
        <option value="Cross-View">Cross View (Main Site)</option>
        <option value="Teepee-Village">Teepee Village</option>
        <option value="Mission-Point">Mission Point</option>
    </select>
</div> <!-- end second-step -->

<div id="last-step">
	<h2>Last Step</h2>
	<p>Please select one of the following payment methods.</p>
	<div>
	    <input type="radio" name="payment" id="payment0" value="Credit Card" /><label>Credit Card</label>
	</div>
	<div>
	    <input type="radio" name="payment" id="payment1" value="Cheque" /><label>Cheque</label>
	</div>

	<input type="submit" name="submit" id="submit" value="submit" />
</div> <!-- end last-step -->


</form>
</body>
</html>
Be Sociable, Share!

Written by Brenley Dueck

 

25 Responses to “Building a jQuery Step-by-Step Form”

  1. Jason Lengstorf Says:

    April 28th, 2009 at 5:42 pm

    No demo? ;)

    The jQuery bit of this is great, but I wonder about the HTML.

    I think you could accomplish the same end result using form-specific tags instead of divs, such as fieldset and legend, which would keep everything a little more semantic and would clean up the unstyled, degraded version as well.

    Just my clean-HTML evangelism coming out… :)

  2. B. Moore Says:

    April 29th, 2009 at 12:22 am

    Ya I agree with Jason.

    Where the hell is the demo at???

  3. Brenley Dueck Says:

    April 29th, 2009 at 9:12 am

    You’re probably right Jason. You could maybe have each fieldset as a “form step”. Thanks for the advice…

  4. Brenley Dueck Says:

    April 29th, 2009 at 9:12 am

    and by the way… the demo is now up :D

  5. William Rouse Says:

    May 30th, 2009 at 9:04 pm

    When the next and previous links are clicked, how does execution go to the following functions?
    $(‘#first-step .prev’).remove();
    $(‘#last-step .next’).remove();

    I ask this because as I sit in the Netbeans debugger I don’t see execution on those two functions when I set a break point?
    Thanks!
    WBR

  6. king Says:

    June 22nd, 2009 at 10:18 am

    how do you add a simple link to access a particular step? example if i was in the div first-step and wanted to add a link to take me to the fifth-step how can i add a link ?

  7. Huyennk Says:

    July 23rd, 2009 at 2:35 am

    It’s great!

    Thank you Brenley Dueck!

  8. Stephan Says:

    October 22nd, 2009 at 8:14 am

    Is it possible to use te Validate-jquery plugin with this script?

  9. kusiu Says:

    December 16th, 2009 at 7:22 am

    So… Who use the Validate jquery plugin in this script? Please help:)

  10. Naoki Says:

    February 1st, 2010 at 6:40 pm

    No demo is found above, where is it?
    Please provide a live link, thanks

  11. Steven Says:

    February 24th, 2010 at 9:38 am

    I’m little unclear on how to create validation for my steps. Anyone give me a hand?

    Thanks

  12. Marianela Lopresto Says:

    March 19th, 2010 at 11:11 am

    Darn nice post. Would it be fine with you if I added your blog to my linkexchange directory?

  13. brenelz Says:

    March 19th, 2010 at 12:08 pm

    go for it!

  14. okan ozkan Says:

    April 11th, 2010 at 10:47 am

    It’s great!

    Thank you.

  15. stanz Says:

    April 15th, 2010 at 8:15 am

    Thanks a lot for taking the time to write this up, I found it very useful with a project I am doing.

  16. Eduardo Says:

    May 27th, 2010 at 2:42 am

    Demo no longer available

  17. alison Says:

    June 16th, 2010 at 1:24 pm

    I would really really appreciate some help on the
    // validate first-step
    // validate second-step etc
    Can you please provide a sample of how this might be integrated. Your demo is not working ??? Otherwise, I think this step-by-step form is really compact and smooth. Thank you and I look forward to hearing from you.

  18. Buzzknow Says:

    October 28th, 2010 at 10:46 am

    ahh…demo not working :(

    pls provide some valid demo ..

    regards

  19. Max Says:

    January 20th, 2011 at 9:34 am

    Demo not available

  20. WarGot Says:

    May 25th, 2011 at 2:45 pm

    No demo, it`s very bad -(

  21. Victoria Says:

    June 15th, 2011 at 10:15 am

    I’d also very much appreciate a demo. :)

  22. Mike Says:

    October 25th, 2011 at 1:09 am

    any demo?

  23. ron Says:

    November 4th, 2011 at 3:27 am

    hi demo does not work

  24. Kennedy Says:

    November 22nd, 2011 at 9:01 pm

    Here is a demo: http://jsfiddle.net/kennedysgarage/pvrAt/

  25. Israel Says:

    August 17th, 2012 at 9:23 am

    Thanks for the demo

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!