In this example, we are learning Javascript local storage to store the list of our bill status. The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.
The localStorage store data in name/value pair and example below we have an example to set and retrieving data from local storage.
What are we learning?
- HTML local storage
- DOM manipulation and event listener of Javascript
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("name", "Gangchenpa");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("name");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
In this example, we have an input box to add new bill with bill status not paid, as in the checkbox with ticked indicate bill paid. We can delete the billing record from the local storage by clicking on icon recycle bin.
Step 1: Add the following code in index.html to display the input box and list of all bill record from local storage when the constructor of a class is called.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Bill Status</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content-area row">
<div class="col-md-2 col-xs-2 col-lg-2 col-sm-2"></div>
<div class="col-md-8 col-xs-8 col-lg-8 col-sm-8">
<h2>Bill payment status </h2>
<div class="row input-area">
<div class="col-md-1"></div>
<div class="form-group col-md-9">
<input type="text" placeholder="New Bill" class="form-control" id="addBill">
</div>
<div class="form-group col-md-1">
<button class="btn btn-primary" onclick="toDo.addBillClick()">Add</button>
</div>
<div class="col-md-1"></div>
</div>
<ul class="list-group" id="billList">
</ul>
</div>
<div class="col-md-2 col-xs-2 col-lg-2 col-sm-2"></div>
</div>
</div><!-- /.container -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="scripts.js"></script>
</body>
</html>
In the highlight ul tag, we are loading all the bill item from local storage when a browser loads the page. We have a function in index.html.toDo.addBillClick(): to add new Bill record to the local storage BILLS object
Step 2: We have to add Javascript code to add, delete bill item to local storage.
class BillClass {
constructor() {
this.bills = JSON.parse(localStorage.getItem('BILLS'));
if(!this.bills) {
this.bills = [
{bill: 'Room rent', isPaid: false},
{bill: 'Electricity bill', isPaid: true},
{bill: 'Internet bill', isPaid: false},
];
}
this.loadBills();
this.addEventListeners();
}
addEventListeners() {
// Add bill
document.getElementById('addBill').addEventListener("keypress", event => {
if(event.keyCode === 13) {
this.addBill(event.target.value);
event.target.value = "";
}
});
}
addBillClick() {
let target = document.getElementById('addBill');
this.addBill(target.value);
target.value = ""
}
addBill(bill) {
let newBill = {
bill,
isPaid: false,
};
let parentDiv = document.getElementById('addBill').parentElement;
if(bill === '') {
parentDiv.classList.add('has-error');
} else {
parentDiv.classList.remove('has-error');
this.bills.push(newBill);
this.loadBills();
}
}
toggleBillstatus(index) {
this.bills[index].isPaid = !this.bills[index].isPaid;
this.loadBills();
}
deleteBill(event, billIndex) {
event.preventDefault();
this.bills.splice(billIndex, 1);
this.loadBills();
}
generateBillHtml(bill, index) {
return `
<li class="list-group-item checkbox">
<div class="row">
<div class="col-md-1 col-xs-1 col-lg-1 col-sm-1 checkbox">
<label>
<input id="togglebillstatus" type="checkbox" onchange="toDo.togglebillstatus(${index})" value=""
class="" ${bill.isPaid?'checked':''}>
</label>
</div>
<div class="col-md-10 col-xs-10 col-lg-10 col-sm-10 bill-text ${bill.isPaid?'Paid':''}">
${bill.bill}
</div>
<div class="col-md-1 col-xs-1 col-lg-1 col-sm-1 delete-icon-area">
<a class="" href="/" onClick="toDo.deleteBill(event, ${index})">
<i id="deleteBill" data-id="${index}" class="delete-icon glyphicon glyphicon-trash"></i>
</a>
</div>
</div>
</li>
`;
}
loadBills() {
localStorage.setItem('BILLS', JSON.stringify(this.bills));
let billsHtml = this.bills.reduce((html, bill, index) => html += this.generateBillHtml(bill, index), '');
document.getElementById('billList').innerHTML = billsHtml;
}
}
let toBill;
window.addEventListener("load", () => {
toBill = new BillClass();
});
What we are learning
- We are using event listener keypress on the input text box and the keyCode 13 indicate enter key.
- Use of reduce() method on bills array object: bills.reduce((Html, bill, index) – to load all the bill record from local storage to accumulator HTML variable and bill is a current element of bills array record.
- Create toBill object when window event listener load the page
window.addEventListener("load", () => {
toBill = new BillClass();
});