1

I am trying push elements to an array dynamically. But my code is not working. I want to add array elements onclick in jquery. When i push an element its getting added but when i am trying to add second element first element is removed and only second element is added. Not able to add elements dynamically.

This is my code to push elements dynamically:

$('#addItemFromAjax').click(function(){
var storage = '{"items":[]}';
var itemObject = JSON.parse(storage);
itemObject["items"].push({"name":data[0].name,"id":data[0].id});
localStorage.setItem('itemList', JSON.stringify(itemObject));
alert(localStorage.getItem('itemList'));
});
3
  • Declare array outside of click function and try it.I guess every time you click, the array is initialized Commented May 31, 2017 at 5:08
  • @Balu Didn't work that way for me Commented May 31, 2017 at 5:10
  • I mean declare the array at global level in the js file where the click function is handled. Commented May 31, 2017 at 5:14

1 Answer 1

3

Try below code. It will use the localStorage list first if available else will initialize it.

Also you are pushing first element from data always, so may need to change as per your requirement!

$('#addItemFromAjax').click(function(){
 var storage = localStorage.getItem('itemList') || '{"items":[]}';
 var itemObject = JSON.parse(storage);
 itemObject["items"].push({"name":data[0].name,"id":data[0].id});
 localStorage.setItem('itemList', JSON.stringify(itemObject));
 alert(localStorage.getItem('itemList'));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.