Save to JSON LocalStorage
by Sub Taper
HTML
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.js"></script>
<div class="container">
<div class="hero-unit">
<h1>JSON SAVING TO LS - ADDING ITEMS</h1>
<ul id="bxs" class="tabs"> </ul>
</div>
</div>
<div class="col-lg-3">
<div class="well">
<div class="form-group row">
<label for="id" class="col-lg-2 control-label">Name</label><input type="text" id="id" class="form-control"/> <label for="cost" class="col-lg-2 control-label">Price</label><input type="text" id="cost" class="form-control"/><button class="btn btn-danger btn-lg">save to JSON</button>
</div>
</div>
</div>
JavaScript
$("button").click(function() {
var productname = $("#id").val();
var worth = $("#cost").val();;
// update the result array
var result = JSON.parse(localStorage.getItem("prodList"));
if(result == null)
result = [];
result.push({id: productname, cost: worth});
// save the new result array
localStorage.setItem("prodList", JSON.stringify(result));
// append the new li
$("#bxs").append($("<li></li>").attr("id", "item-"+productname).html(worth));
});
// on init fill the ul
var result = JSON.parse(localStorage.getItem("prodList"));
if(result != null) {
for(var i=0;i<result.length;i++) {
var item = result[i];
$("#bxs").append($("<li></li>").attr("id", "item-"+item.id).html(item.cost));
}
}