I'm trying to create an array and store it in localStorage on click.
I can do this using the following code. this code will create an array when the buttons are clicked but I need to be able to remove the same value again if the same button is clicked again.
But my code only adds (push) the values to the array and it doesn't remove it.
I know my issue is from where I need to look in the array for the value that I added but I don't have any idea how to do this.
This my code:
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
$(document).on('click', ".addToFavBtn", function(e) {
var id = $(this).attr('id');
var title = $(this).attr('data-cont');
var item = e.target;
var index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id)
return;
if (index == -1) {
var myarray = {
id: id,
title: title
};
favorites.push(myarray);
} else {
favorites.splice(index, 1);
}
localStorage.setItem('favorites', JSON.stringify(favorites));
console.log(favorites);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="addToFavBtn" id="12321" type="button" data-cont="test 1.1" value="test 1">
<input class="addToFavBtn" id="1" type="button" data-cont="test 1.3" value="test 1.3">
<input class="addToFavBtn" id="12" type="button" data-cont="test 1.44" value="test 1.44">
<input class="addToFavBtn" id="271" type="button" data-cont="test 66" value="test 66">