document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);
}
e.preventDefault();
}
there is no error if
if(localStorage.getItem('bill')==null)
but there comes error at else as
Uncaught TypeError: Cannot read property 'push' of undefined
at HTMLFormElement.saveItem
the data is stored when the local storage is empty but cannot add data if it is not.
Can you please check what is the result of JSON.parse(localStorage.getItem('bill'));
? Is its a valid array?
Your expense is a object, you need to save the bill inside the local storage.
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.