i want to have an array (converted also to a localStorage value) box where the value of '#textInput' is added to the localStorage each time, however after refreshing and entering a new value, the new value is not added to the localStorage, but replaces it. I believe this is because after refreshing the data from users[] is set to null, but dont know how to fix it
var users = new Array();
var valueChanger = 1;
alert(localStorage.getItem('usernames'));
function addValue() {
var newUser = $('#textInput').val();
users.push(newUser);
localStorage.setItem('usernames', users);
alert(localStorage.getItem('usernames'));
}
You have to rewrite your code like the below to make it working,
var users = JSON.parse(localStorage.getItem('usernames')) || [];
var valueChanger = 1;
alert(localStorage.getItem('usernames'));
function addValue() {
users.push($('#textInput').val());
localStorage.setItem('usernames', JSON.stringify(users));
alert(localStorage.getItem('usernames'));
}
Since localStorage only stores string, we need to stringify the array before storing and Parse it before reading.
Everytime, when page refreshes you're first statement creates new array instead of using old one.
var newUser = localStorage.getItem('usernames') || "";
var valueChanger = 1;
var users = [newUser];
alert(localStorage.getItem('usernames'));
function addValue() {
var newUser = $('#textInput').val();
users.push(newUser);
localStorage.setItem('usernames', users);
alert(localStorage.getItem('usernames'));
}
Thanks & Cheers :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With