Clicking on the list from down should save the item to an array in local storage.
$(document).ready(function() {
$( 'ul.namelist>li' ).on( "click", function() {
var items = [];
items.push( $( this ).text() );
localStorage.setItem("items",items);
});
})
HTML
<ul class="namelist">
<li>John</li>
<li>Leena</li>
<li>Paul</li>
<li>Vaughn</li>
<li>Aneel</li>
<li>Jason</li>
</ul>
This code stores only last clicked name in the array where as I am trying to store all clicks in it as [John,Paul,Leena] etc. Please help.
2 Answers 2
Your clicks are overriding the stored data in every click, you may need to fetch the existing store and update it before pushing a new one.
Also, your localStotrage would only store strings so you would need to convert the array to a string before storing it.
$( 'ul.namelist>li' ).on( "click", function() {
var items = localStorage.get('items') ? JSON.parse(localStorage.get('items')) : [];
items.push( $( this ).text() );
localStorage.setItem("items", JSON.stringify(items));
});
})
2 Comments
Local storage holds data as a string, so, do JSON.stringify() before storing it to local storage. Also, fetch the current state from storage before making any updates.
$('ul.namelist>li').on("click", function() {
var items = localStorage.getItem('items') ? JSON.parse(localStorage.getItem('items')) : [];
items.push($(this).text());
localStorage.setItem("items", JSON.stringify(items));
});
localStoragecan only store strings. TrylocalStorage.setItem('items', JSON.stringify(items)). Of course, each time you click an<li>, you will only ever store an array of length1