Im trying to store multiple student objects (built from a form submission) into session storage and then eventually loop over session storage and display them on a page. Im not very familiar with any of this and its my first crack at it... How do i store multiple students ? i feel like i need an append... im just overwriting every time... Thanks !
btw... must be pure JS
HTML
<div id="infoStyle" class="col-lg-6 center-block infoWindow animated">
<span class="glyphicon glyphicon-user" aria-hidden="true"></span>
<h4>First Name : <input id="fName" type="text" pattern="[A-Za-z]{50}" title="50 characters or less"></h4>
<h4>Last Name : <input id="lName" type="text" pattern="[A-Za-z]{50}" title="50 characters or less"></h4>
<h4>Email Address : <input id="email" type="email"></h4>
<br>
<a onclick="createStudent()" class="btn btn-info" role="button">Create Student</a>
<br><br>
<a onclick="cancel()" class="btn btn-danger" role="button">Cancel</a>
</div>
JS
function createStudent(){
var student = new Object();
student.fName = document.getElementById('fName').value;
student.lName = document.getElementById('lName').value;
student.email = document.getElementById('email').value;
sessionStorage.setItem('student', JSON.stringify(student));
var retrievedObject = sessionStorage.getItem('student');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
1) You need to store into an array
, but before that you will need to check if the array student already exists on sessionStorage or not.
2) Then add a new student to the array, and store it into localstorage
3) while you retrive the data there is no change, it correct what you have written
function createStudent(){
// this is how you set it
var newStudent = new Object();
newStudent .fName = document.getElementById('fName').value;
newStudent .lName = document.getElementById('lName').value;
newStudent .email = document.getElementById('email').value;
if(sessionStorage.student)
{
student= JSON.parse(sessionStorage.getItem('student'));
}else{
student=[];
}
student.push(newStudent )
sessionStorage.setItem('student', JSON.stringify(student));
// this is how you will retrive it
var retrievedObject = sessionStorage.getItem('student');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
}
Here is the jsfiddle