How to remove specific item from local storage array? - javascript

I'm building a 'to do list' , The user appends new notes to the list after clicking .
I saved all the appended data in the local storage.
Now i want to remove the clicked note from the array and save it back to the local storage.
I have this code:
**//Here i get the note**
var getNote = JSON.parse(localStorage.getItem("savedNotes")) || [];
$("#notes-section").append(getNote);
**//Here i set the note**
getNote.push(note);
localStorage.setItem("savedNotes", JSON.stringify(getNote));
**//Here i want to remove the note from the array**
$(document).on('click', '.pin', function() {
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000);
for(var i =0 ; i < getNote.length; i++ ){
getNote.splice(i,1);
localStorage.setItem("savedNotes", JSON.stringify(getNote));
}
});

As stated in comments you need to provide only relevant code, but just to clear things out here, the way to go here is:
To have an empty array of notes.
Add this array to localStorage via localStorage.setItem("savedNotes", JSON.stringify(notes)).
Every time you add a note you will need to: parse this array back from localStorage with notes = JSON.parse(localStorage.getItem("savedNotes")).
Then push the new note into this array via notes.push(note).
Then set this item again with localStorage.setItem("savedNotes",
JSON.stringify(notes)), it will update your existing item in the localStorage.
It all relies on Storage.getItem() and Storage.setItem() methods.
And to remove a note from the array you need to do the same thing, expect that you will search for this note in the parsed array and remove it.

Related

Display different text everytime you call onclick function

I have this code where I am trying to pull users from my firebase database:
function pullFromDB(){
usersRef.on('value', function(snapshot) {
function next_user(){
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
}
So far it will return just one of the users as I believe it must be going through the whole users array and then putting the last name into the "users" element.
How can I iterate to the next item in the array and display a different name every time I click a button?
I have no idea what's return from DB but first try the console.log() to see what's the type of result. This will give you the answer if you are working on array or other data type.
Then if it's an array, your code:
for (user in snapshot.val().users){
document.getElementById("users").innerHTML = user
}
It iterates the whole array and .innerHTML puts user string as the last iteration. If you want to change it each time you click a button you need a variable that will contain inteager of index that's currently aplied to id="users".
Then for each click you need to increase the variable by one.
Here is an example of working with arrays in JS. http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_element
Your are iterating through the whole array and only the last one is possible shown. You just need to assign an index and use it.
I don't know your remaining code, but by the given information, this should to the trick:
i = 0;
function pullFromDB(){
usersRef.on('value', function(snapshot) {
lastnames = Object.keys(snapshot.val().users); // get all keys, in your case the last names
function next_user(){
user = lastnames[i];
document.getElementById("users").innerHTML = user;
i++; // increase after click
// when you want to access more information of the user, you can do it like this (as an example)
// user_id = snapshot.val().users[user].id;
}

how to remove element from session storage array when there are lot of

I am trying to remove elements from localStorage array. all i could find is localStorage.removeItem(key);
I couldn't understand how it works because I have 2 sessionStorage. is that okay?
I have this so far
var theCart = JSON.parse(sessionStorage.getItem("ProductName")); // Retrieving
var quantity = JSON.parse(sessionStorage.getItem("QuantityOFprod"));
var prodprice = JSON.parse(sessionStorage.getItem("sum"));
ProductName, QuantityOFprod and sum is arrays.
I don't now how to form the localstorage.removeItem to select the array and then select an element inside the array. I have tried this
sessionStorage.removeItem("ProductName", JSON.stringify(namee));
namee is the a variable which contains the element I want to delete inside the specific sessionStorage array. But all it was doing is deleting everything.
You have to do this way:
read the entry
decode from JSON
remove the element
encode to JSON
update the entry
tmp = JSON.parse(sessionStorage.getItem("ProductName"));
delete tmp["key to remove"];
sessionStorage.setItem("ProductName", JSON.stringify(tmp));
Done.

AngularJs pushing multiple values from array to another with databinding refreshing

I am getting an array from the server which can contain 0..n elements in an array. I then add that to array I use locally for databinding (basically cache data in client). When doing it this way databiding works without any problems:
for (var i = 0 ; i < data.Result.length ; i++) {
scope.cachedData.push(data.Result[i]);
}
Meaning - view refreshes, everything works. But when I try: scope.cachedData.concat(data.Result); it won't work. Why is that?
If you want to push everything in a single instruction use apply without breaking the reference to scope.cachedData
Array.prototype.push.apply(scope.cachedData, data.Result);
Also, I know this is a little bit off topic but if you want to insert at a specific index you can use splice with apply
// I definitely want to prepend to my array here
var insertionIndex = 0,
// we don't want to delete any elements here from insertionIndex
deleteCount = 0;
// Because we use apply the second argument is an array
// and because splice signature is (startIndex, noOfElementsToDelete, elementsToInsert)
// we need to build it
Array.prototype.splice.apply(scope.cachedData, [insertionIndex, deleteCount].concat(data.Result));
Imagine your array scope.cachedData = [3,4]; and data.Result = [1,2];, with the code above scope.cachedData will become [1,2,3,4].

dynamic array to local storage/jstorage?

I am pushing values in to my array every 10 seconds which is being displayed by innerHTML on a div.
Onreload or on visit to some other web page I want to display the already pushed content and the content being pushed presently.
I have gone through local stroage and jstorage tutorials.
This is what I am doing precisely=:
localStorage.setItem('names', xyz);
I know how to store one variable,but what when we have a dynamic array being updated/10sec and data being pushed in it every 10 seconds.how do I set and get this dynamic array even when I go to some other link.
If you are interested in my code:http://jsfiddle.net/vCcnB/
UPDATE 1----for simplification(ignore if you have understood.)
This is what is being displayed in my div.Page1 indicates the page and 0,10,20 indicates time.
# 10 seconds----[page1,0]
[page1,10]
#20 seconds-----[page1,0]
[page1,10]
[page1,20]
now a click to some other page.
#10 seconds----[page1,0]
[page1,10]
[page1,20]
[page2,0]
[page2,10]
now a click to some other page.
#20 seconds----[page1,10]
[page1,20]
[page2,0]
[page2,10]
[page3,0]
[page3,10]
[page3,20]
You can use json object for this like,
localStorage.setItem('names', {'ABC','XYZ'}); //and so on
or json string like
var json={'ABC','XYZ'};
localStorage.setItem('names', JSON.stringify(json)); //and so on
To get an existing item try this,
console.log(localStorage.getItem('names'));
Read this https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage
You have to JSON.stringify and JSON.parse your array to store and load it respectively.
// initialize
var myArray = [];
// load saved array
if(window.localStorage["savedArray"] != null)
myArray = JSON.parse(window.localStorage["savedArray"]);
// modify array
myArray.push("abc123");
// re-save array
window.localStorage["savedArray"] = JSON.stringify(myArray);

How to limit storage of data onto local storage and retrieve it?

Hi I need to limit the data being added onto my local storage. I only need 5 items to be stored if the user adds the 6th item the first item should be removed. I accomplished that portion but when retrieving it, it retrieves the removed data and skips on the fourth item. Any ideas?
how i set things
var _i = 0 //global;
storage.setItem(_i, URL);
checkLimit
if(storage.length >= 5)
{
var _a = storage.getItem(0);
storage.removeItem( _a );
_a += 1;
}
When retrieving it
for( var _x = 1; _x <= storage.length - 1; _x++)
{
var _url = storage.getItem(_x);
}
update
oh i forgot to mention that when i use key index to get item it doesnt display the removed data but somehow skips the fourth one.
update 2
Now it doesn't skip the fourth record but it shows the removed data and doesn't show the last added data. e.g
the //first
avengers //second
are //third
coming //fourth
now //fifth
excited //sixth
Since i specifically limit it to five (5) the should be removed from the list and excited should be added. its doing fine but when i close the application and try to retrieve the data it returns
the
avengers
are
coming
now
and it doesn't shows excited Am i making sense?
You can't rely on the order of Web Storage keys. Check this question: HTML5 localStorage key order
If you want to do this, just use an array object which will be stored in localStorage.

Categories

Resources