Registration App using HTML 5 Local Storage

By | April 26, 2011

Today we are going to create an event registration app using HTML 5 local storage to hold all the information. In a previous post we looked at how to implement local storage and created a quick example to show how it works but this is ok but I know myself I like to see a true working demo to really get my head around how things work. Luckily whilst at work one of my colleagues came to me a dilemma. The sales people were doing an exhibition, the problem was they wanted a way to register customers who came to the stand but they weren’t sure if they would have internet access all the time. Now I’m sure this could have been built in excel but we wanted a stylish way of doing things and our skills are in front end web design.
We had about three hours to do this project (because these huge exhibitions just sneak up on the sales people don’t they?) so we had to come up with our answer quickly, well it just so happened that a few weeks before yours truly had written a blog post about local storage so I suggested this would be a great way to get round the problem. Set the app up to run off local storage then host the files locally on the sales peoples laptops and no worries about internet connections. The resulting app worked so well that the rest of the business want their own version.
View DemoDownload Source

Application Structure

The application that I’m going to show you today is slightly modified from the version my colleague and I created in those 3 hrs. this is going to be how I would have liked to have done it.
There will be 3 html files index.html, thankyou.html and admin.html. Then along with the jQuery library there will be 2 javascript files, form.js and admin.js and finally the css file, styles.css. I’m only going to concentrate on the main files which are the index.html, admin.html, form.js and admin.js. So here goes.

Index.html

The index.html file will consist of an html5 form complete with html5 validation and placeholders and it will also be styled using CSS3 styles. So lets have a look at the code.





Registration Form




Your Logo Here

Registration form





CD | Paper
Offer & Price Deals
Market & Industry Information

I have read and accepted the Terms & Conditions

Please complete all mandatory fields above and try again.

So we’ve got the html5 doctype declaration at the top relevant meta tags then we bring in the css file. Nothing new here hopefully. Then we have our header tag with the logo placeholder and the site wide navigation held in the nav tag.
After this we go into our form. It’s a pretty straight forward form the only thing here really to take note of is the required and placeholder attributes on the first few four input fields and the type of the email input which is set to email. The required attribute means that these inputs must have something in them when they are submitted or the form won’t submit and the added type=”email” means the browser will require that input to be formatted as an email. The place holder attribute adds a helpful bit of text to the input field before anything is typed in there. These are really nice touches that used to take javascript to create. I will be looking more at form elements in a future post.
At the bottom of the page I bring in two javascript files the jquery library and the form.js file. I’m not going to dwell on the the CSS styling in this post as the main point to the tutorial was to show how local storage can work in an app.

form.js

So as with previous javascript examples I have done I will use my pseudo code to explain what we want this file to do.

Check to see if the browser supports local storage functionality
if it doesn't show a message to tell the visitor this page will not work correctly
if it does support it then
collect all the values from the form on submit
add them to the browsers local storage area

So this file doesn’t need to do much really. Check for browser support the put all the values from the form into local storage so we can retrieve them later. Easy….. Actually it is……ish.

$(document).ready(function() {
        if (!window.localStorage) {
            alert('Your browser does not support HTML5 localStorage. Try upgrading.');
        } else {
            $("#return_form").submit(function(){
	                    setAllItems();
            });						
	}
});

var setAllItems = function(){
	var newDate, itemId, formSave;
	newDate = new Date();
        itemId = newDate.getTime();
        formSave = {
        	fname : $("input[name='firstname']").val(),
        	lname : $("input[name='lastname']").val(),
        	email  :$("input[name='email']").val(),
		phone : $("input[name='phone']").val(),
        	job : $("select[name='job']").val(),
        	primeuse : $("select[name='primeuse']").val(),
		cd : $("input[name='cd_catalogue']").attr('checked'),
        	paper : $("input[name='paper_catalogue']").attr('checked'),
        	priceDeals : $("input[name='price_deals']").attr('checked'),
		industryInfo : $("input[name='industry_info']").attr('checked')
	};
						
	// turn data into JSON string
	localStorage.setItem( itemId, JSON.stringify(formSave));
	};

So we use the incredibly handy jquery function $(document).ready to make sure all the elements on the page have been loaded. Then we do our browser support check. If we have support we attach the function setAllItems() to the submission of the form. So basically when the form is submitted that function will fire. So it is this function that does all the magic.
First we need to create a unique id for our item so we can place it in the local storage without the fear of deleting anything else. My colleague came up with the idea of using the time object as the id. Nobody would input their deatails at exactly the same time so this was perfect. so we create a new Date object then use the getDate() method and assign it to itemId for our unique identifier. Next we create another object and assign the values from the form to different properties of this object. This is called JSON (JavaScript Object Notation) and is a brilliant way of holding lots of data, to read more on this go to json.org but for our purposes just know this is the best way to hold the form information. But now we have an issue because the local storage object will only hold information as a string and we have an object. Luckily modern browsers have built in JSON support so we can use the stringify method to turn our JSON object into a string. We do this at the same time as setting the item in local storage and assigning the unique id. So the final says “Set a new item in local storage with the id of itemId and a value of the JSON object turned into a string.
Still with me good because now we’re onto the admin page which is where we retrieve the data from local storage.

admin.html





Registration Form | Admin



Your Logo Here

First Name Last Name Email Address Telephone Number Primary job role? Primary use for the product CD catalogue Paper Catalogue Price Deals Industry Information

The admin.html file is basically a container for the data that we bring back from local storage. So the only thing really here to talk about is the table element with the column headings, this is where we are going to append the data once we have recovered it and formatted it as HTML. The other thing to take note of is the is the button “RESET LIST” that we will attach an event to using jQuery. We will also use jQuery to add some nice embellishments to the page but we will talk about those in a minute.

admin.js

$(document).ready(function() {
        if (typeof(localStorage) === 'undefined' ) {
            alert('Your browser does not support HTML5 localStorage. Try upgrading.');
        } else {
	    //load the items
            getItems(); 
        }
    });
	
var getItems = function() {
	
	var timeLog, logLength, i;
				
        i = 0;
        logLength = localStorage.length-1; //how many items are in the database starting with zero
        rowLog = '';

        //now we are going to loop through each item in the database
        for (i = 0; i <= logLength; i++) {
	    var itemKey, value, values, firstname, lastname, email, phone, job, primeuse, cd_catalogue, papaer_catalogue, price_deals, industry_info;
            //lets setup some variables for the key and values
            itemKey = localStorage.key(i);
						
            value = localStorage.getItem(itemKey);
	    values = JSON.parse(value);
            firstname = values.fname;
            lastname = values.lname;
            email = values.email;
	    phone = values.phone;
	    job = values.job;
	    primeuse = values.primeuse;
	    cd_catalogue = values.cd;
	    paper_catalogue = values.paper;
	    price_deals = values.priceDeals;
	    industry_info = values.industryInfo;

            //now that we have the item, lets add it to the table
            rowLog += ''+firstname+''+lastname+''+email+''+phone+''+job+''+primeuse+''+cd_catalogue+''+paper_catalogue+''+price_deals+''+industry_info+'';
        }

        $("#theLog").append(timeLog); //update the table with the list items
				
	    $(".tableRow").mouseenter(function() {
		$(this).children().children(".delete").show();
	    });
	    $(".tableRow").mouseleave(function() {
		$(this).children().children(".delete").hide();
	    });
				
	    $("#reset_list").click(function() {
		//alert("clicked");
		localStorage.clear();
		getItems(); 
	     });
				
	     $(".delete").click(function() {
		var itemId = $(this).parent().parent().attr('id');								
		//alert(itemId);
		localStorage.removeItem(itemId);
	        getItems(); 
	     });
    }

So this is where it all happens lets take it from the top.
First we use the jQuery document load again to make sure the page has loaded then we check that the browser has compatibility, if not then we show an alert if yes then we run the getItems function.
In the getItems function we create the variables first and then assign values to two of them, these are going to be used in our for loop. The clever one here is loglength that find out how many items are held in local storage and assigns them to a variable. Then we use the for loop to get the id for each item from localStorage and then pull out the stringified JSON object and parse it back to a JSON object and then we assign the different values back to variables. Once this has been done we create a tr element and add the variables to the HTML to create a table row with the information from local storage. Once this is done for one item we update the rowLog variable and start again for the next item. Once we have all the items out of the local storage and into the rowLog variable we append that variable (which is just full of html) to the table in our file.
The rest of the functions are just to add a little more to the app. So first we have the mouseenter and mouseleave on the tableRows. This shows an element with an id of delete (this element has a css property of display:none) when you hover (mouseenter) and hides it again when you move the cursor away(mouseleave).
Next we have the click event attached to the reset button. This just calls the localStorage function clear() which just deletes everything from localStorage then we call the getItems function again to update the table which will of course be empty.
Lastly we have the click event attached to the delete button. In the original for loop we add the itemId to the row as an id for the tr element. Then by accessing this id we can delete an individual item from localStorage then ofcourse we run the getItems function to update the html in the table.
And that’s it hope you enjoyed the post.
View DemoDownload Source

7 thoughts on “Registration App using HTML 5 Local Storage

  1. ken

    Hi Matt

    Great educational tutorial. Thanks.

    I was working on a HTML5 /JavaScript test app but i am having some difficulty.
    I was wondering if you could help me out I would very much appreciate it.I can share the app if you let me know your email.

    Reply
  2. binay

    hi boss ,it is very useful to me but can you please tell me how to retrieve those data in another form and validating with the user given data and submit the form successfully.
    basicaly what i want to sat aperson do signup in a registration form and later he comes and login with that credential for successful login.how to do this?

    thanks in advance..:)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *