How to #1- How to use Html5 Local Storage
In this How to #1, we are going to see how to use Html5 Local Storage by storing a simple JSON object into Local storage,retrieving and removing it from Local storage.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="https://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { //Binding SaveValue button click event //Save the UserDetails to the JSON object in the local storage. $('#SaveValue').click(function () { setuserdefinedvalue(); }); //Binding Get value button click event //Gets the UserDetais JSON object in the local storage. $('#GetValue').click(function () { getStoragevalue(); }); //Binding Remove value button click event. //Remove the UserDetails JSON object in the local storage. $('#RemoveValue').click(function () { removevalue(); }); }); //Save the UserDetails to the JSON object in the local storage. function setuserdefinedvalue() { var userDefinedUserDetails = { 'UserDetails': { 'FirstName': $('#FirstName').val(), 'LastName': $('#LastName').val(), 'Age': $('#Age').val() } }; localStorage.setItem('UserDetails', JSON.stringify(userDefinedUserDetails)); //Clearing input fields $('#FirstName').val(''); $('#LastName').val(''); $('#Age').val(''); } //Getting the Values from Local storage. function getStoragevalue() { if (localStorage.getItem('UserDetails') !== null) { var storageData = $.parseJSON(localStorage.getItem('UserDetails')); $('#FirstName').val(storageData.UserDetails.FirstName); $('#LastName').val(storageData.UserDetails.LastName); $('#Age').val(storageData.UserDetails.Age); } } //Remove the UserDetails JSON object in the local storage. function removevalue() { localStorage.removeItem('UserDetails'); } </script> </head> <body> <div> <b>First Name:</b> <input type="text" name="Name" id="FirstName" placeholder="First Name" /> <b>Last Name:</b> <input type="text" name="Age" id="LastName" placeholder="Last Name" /> <b>Age:</b> <input type="text" name="Age" id="Age" placeholder="Age" /> </div> <br /> <div> <input type="button" value="Save Value" id="SaveValue" /> <input type="button" value="Get Value" id="GetValue" /> <input type="button" value="Remove Value" id="RemoveValue" /> </div> </body> </html>
Now let us enter some details in the input fields and click on Save value button.and you can see the saved value in the console output by calling,
localStorage.getItem(‘key’)
Now click on Get value button,you can see the populated input fields from the local storage variable value.
Happy coding !!!