Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Creating a CRUD form with HTML5 Local Storage and JSON

See in this article how to create a simple CRUD program, inputing data in the HTML5 Local Storage and JSON.

For those that don't know yet the Local Storage, this is a HTML resource that works, let we say, like a cookie that doesn't have expiration time. Or else, it is a local to store data that are not lost at the end of the section, thus, we can close and open the browser several times and the information will remain there.

In this article, we'll see how to use the Local Storage in practical terms, creating a simple cadastration program of clients, with CRUD basic operations. We are not going to describe the design that should be used, but the functionaties. In the source-code available in the top of this page, interface is enhenced.

Listing 1: HTML structure

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
	<script type="text/javascript" src="http://code.jQuery.com/jQuery-1.7.2.min.js"></script>
	<script type="text/javascript" src="functions.js"></script>
</head>
<body>
	<form id="frmCadastre">
		<ul>
			<li>
				<label for="txtID">ID:</label>
				<input type="text" id="txtID"/>
			</li>
			<li>
				<label for="txtName">Name:</label>
				<input type="text" id="txtName"/>
			</li>
			<li>
				<label for="txtPhone">Phone:</label>
				<input type="text" id="txtPhone"/>
			</li>
			<li>
				<label for="txtEmail">Email:</label>
				<input type="text" id="txtEmail"/>
			</li>
			<li>
				<input type="submit" value="Save" id="btnSave"/>
			</li>
		</ul>
	</form>

	<table id="tblList">

	</table>
</body>
</html> 

It is important to observe that we make reference to two JavaScript files. The first one is JQuery and the second one is the file containing the functions that will treat the cadastration itself.

Throughout this article, we'll use some functions of JavaScript that deserve special attention, are they:

  • localStorage.setItem(name, value): this function is used to store a value in the Local Storage. Each object stored is referenced by a key (name)
  • localStorage.getItem(name): On the other hand, the getItem is used to recover a value stored from it's identifying key.
  • JSON.stringfy(object): In order to store the data, we'll use the JSON format and this function transforms one object into string with a syntax adequate to the JSON.
  • JSON.parse(object): Since the function parse transforms an item in JSON format into it's original format.

From here, shall we create then our file functions.js and into it we'll use also the syntax jQuery, thus, all content shall be in the body of the function that is executed on the loading of the page.

Listing 2: Global variables definition
$(function(){
	var operation = "A"; //"A"=Adding; "E"=Editing
	var selected_index = -1; //Index of the selected list item
	var tbClients = localStorage.getItem("tbClients");//Retrieve the stored data
	tbClients = JSON.parse(tbClients); //Converts string to object
	if(tbClients == null) //If there is no data, initialize an empty array
		tbClients = [];
}); 

The variable "operation" will be used in order to define if the user is adding or editing a register. "selected_index" will serve to reference the register selected in a table. "tbClients" is ours "table of clients" and we start it with the value recovered from the Local Storage (saved with the key "tbClients"). In the case there's no content, then the variable will be initialized as an empty arrow.

By default, the variable "operation" will have the value "A", in other words, may the user type the data and click in the button to save the information, a new register will be added, except when one have clicked in the table in order to edit it.

Now, let’s go to the CRUD functions. We'll use 4 functions: Add, Edit, Delete e List. Let us see the code:

Listing 3: Add function

function Add(){
	var client = JSON.stringify({
		ID    : $("#txtID").val(),
		Name  : $("#txtName").val(),
		Phone : $("#txtPhone").val(),
		Email : $("#txtEmail").val()
	});
	tbClients.push(client);
	localStorage.setItem("tbClients", JSON.stringify(tbClients));
	alert("The data was saved.");
	return true;
} 

Listing 4: Edit function

function Edit(){
	tbClients[selected_index] = JSON.stringify({
			ID    : $("#txtID").val(),
			Name  : $("#txtName").val(),
			Phone : $("#txtPhone").val(),
			Email : $("#txtEmail").val()
		});//Alter the selected item on the table
	localStorage.setItem("tbClients", JSON.stringify(tbClients));
	alert("The data was edited.")
	operation = "A"; //Return to default value
	return true;
} 

Listing 5: Delete function

function Delete(){
	tbClients.splice(selected_index, 1);
	localStorage.setItem("tbClients", JSON.stringify(tbClients));
	alert("Client deleted.");
} 

Listing 6: List function

function List(){		
	$("#tblList").html("");
	$("#tblList").html(
		"<thead>"+
		"	<tr>"+
		"	<th></th>"+
		"	<th>ID</th>"+
		"	<th>Name</th>"+
		"	<th>Phone</th>"+
		"	<th>Email</th>"+
		"	</tr>"+
		"</thead>"+
		"<tbody>"+
		"</tbody>"
		);
	for(var i in tbClients){
		var cli = JSON.parse(tbClients[i]);
	  	$("#tblList tbody").append("<tr>"+
								 	 "	<td><img src='edit.png' alt='Edit"+i+"' class='btnEdit'/><img src='delete.png' alt='Delete"+i+"' class='btnDelete'/></td>" + 
									 "	<td>"+cli.ID+"</td>" + 
									 "	<td>"+cli.Name+"</td>" + 
									 "	<td>"+cli.Phone+"</td>" + 
									 "	<td>"+cli.Email+"</td>" + 
	  								 "</tr>");
	}
} 

It is important to observe that in the first column of the table, it is added two images that will serve as buttons of Edit and Delete actions, which event onClick will be treated by jQuery means in the future. The images "edit.png" and "delete.png" are available in the source-code, but also may be any two images (here was used 16x16 dimension images as for the buttons to appear discreet on the table).

The List function should be called in the body of the main function, in order to the table be actualized whenever the site be reloaded.

Now, what's left is treat the events of the HTML's controls that will trigger the functions of CRUD. To store the data again in the register or in the on editing register, we'll use the event onSubmit of the form frmCadastre. See the following code:

Listing 7: Event onSubmit of the form

$("#frmCadastre").bind("submit",function(){
	if(operation == "A")
		return Add();
	else
		return Edit();		
}); 

To the Edit and Delete buttons, on the other hand, were given classes "btnEdit"and "btnDelete", from which we'll treat the following onClick event:

Listing 8: onClick event of the edit buttons

$(".btnEdit").bind("click", function(){
	operation = "E";
	selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
	var cli = JSON.parse(tbClients[selected_index]);
	$("#txtID").val(cli.ID);
	$("#txtName").val(cli.Name);
	$("#txtPhone").val(cli.Phone);
	$("#txtEmail").val(cli.Email);
	$("#txtID").attr("readonly","readonly");
	$("#txtName").focus();
}); 

Listing 9: onClick event of the Delete buttons

$(".btnDelete").bind("click", function(){
	selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
	Delete();
	List();
}); 

The routines used are pretty simple, Here we didn't concern ourselves about validations and error treatment, for instance. Therefore, in the source-code of the article the code is a little bit more complex, with some more functionalities.

The code running on the browser

Figura 1: The code running on the browser

So, as for today that's all folks. I put myself at disposal to answer any questions about the article, you just need to comment right below.

A big hug and shall we meet in the next article.

See also



Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login