0

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.

SMAKSS
10.6k3 gold badges26 silver badges38 bronze badges
asked May 11, 2020 at 5:16
1
  • localStorage can only store strings. Try localStorage.setItem('items', JSON.stringify(items)). Of course, each time you click an <li>, you will only ever store an array of length 1 Commented May 11, 2020 at 5:20

2 Answers 2

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)); 
});
})
answered May 11, 2020 at 5:21
Sign up to request clarification or add additional context in comments.

2 Comments

Have to stringify the array also to set in storage
@charlietfl Right, had missed that.
0

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));
});

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.