Tuesday, 15 August 2017

How to store New JSON Data in sessionStorage | Use JSON Parse and JSON Stringify

How to store New JSON Data in sessionStorage




  • A sessionstorage object is it also used to store a JSON data. 
  • It exists as a property of the window object. 
  • getItem(key-name) = retrieves the value. 
  • setItem(key-name, value) = sets the value for the given key-name.

Index.html


<html>
    <head>
   <title>W3tricks</title>
    </head>

<body>
<div id="output"></div>
<label>Enter New Value</label>
<input type="text" id="myvalue" value=""/>
<script src="script.js"></script>
</body>
</html>


Script.js


var student = '{"student1" : {"name" : "Bob", "age" : "18", "city" : "new york"}, "student2" : {"name" : "Alice", "age" : "16", "city" : "paris"}}';
var MyValue = document.getElementById('myvalue');
var MyObj = JSON.parse(student);
var sendAjax = JSON.stringify(MyObj);
document.getElementById('output').innerHTML = sessionStorage.getItem('MyVal');

if(sessionStorage.getItem('MyVal')){
MyObj = JSON.parse(sessionStorage.getItem('MyVal'));
MyValue.value = MyObj.student1.name;
}

MyValue.onchange = function(){
MyObj.student1.name = this.value;
sendAjax = JSON.stringify(MyObj);
sessionStorage.setItem('MyVal', sendAjax);
document.getElementById('output').innerHTML = sessionStorage.getItem('MyVal');
}

Output - 1



Output - 2



0 comments:

Post a Comment