How to Edit and Remove item from sessionStorage - javascript

This code to store items in sessionStorage so i want to add, edit ,
remove item and remove all my code worked well except remove item i
don't know the reason
function clearItem () {
for (var i = 0; i < sessionStorage.length; i++) {
var a = sessionStorage.key(i);
var b = sessionStorage.removeItem(a);
}
}
here's my code in jsfiddle

function clearItem () {
for (var i = 0; i < sessionStorage.length; i++) {
var a = sessionStorage.key(i);
sessionStorage.removeItem(a);
}
}

You have several problems:
You have indicated that you only want to remove the phone number from sessionStorage here. In this case, there is no need to loop over sessionStorage at all. Just remove that one entry:
sessionStorage.removeItem("number");
In looking over the Fiddle that you provided, your code was quite disorganized and didn't make much logical sense from a "flow" perspective. I have modified it to a working version available here. The biggest issues with your code was that you are trying to loop over sessionStorage when saving and retrieving the values, when what you should have been doing is simply creating key/value pairs of data and accessing the data with the key names you've created.
Read about sessionStorage here

Related

Trying to make sense of "this" in my javascript code (one thing works, the other doesn't)

I've been trying to learn javascript by refactoring some Jquery examples in a book into javascript. In the following code I add a click listener to a tab and make it change to active when the user clicks on the tab.
var tabs = document.querySelectorAll(".tabs a span");
var content = document.querySelectorAll("main .content li");
for (var tabNumber = 0; tabNumber <= 2; tabNumber++) {
tabs[tabNumber].addEventListener("click", function (event) {
for (var i = 0; i < tabs.length; i++) {
tabs[i].classList.remove("active");
}
tabs[tabNumber].classList.add("active");
for (var i = 0; i < content.length; i++) {
content[i].innerHTML = "";
}
event.preventDefault();
});
}
This returns an undefined error when I run it. However, I tried replacing tabs[tabNumber].classList.add("active") with this.classList.add("active") and it worked.
Why doesn't the previous code work? As far as I can see they are referring to the same thing, and tabs[tabNumber] should work since at that point in the code it is tabs[0].
If use this, I think it's better and a more polished solution. If you still want to use tabNumber, it's probably evaluating to 3 in every click callback, because it's the number after the last iteration, and you don't have a tabs[3] position.
So, you just have to make a closure of the tabNumber variable.
I guess other answers told you why tabs[tabNumber] does not work (because it comes from the score of the for loop and so, is always equal to the greater value of tabNumber).
That's why I would recommend using a .forEach loop. Careful though because it doesn't work on arrays of DOM nodes produced by document.querySelectorAll(), but you can use:
// ES6
Array.from(document.querySelectorAll('...'))
// ES5
[].slice.call(document.querySelectorAll('...'))
Anyway, I made a simplified working demo of your code.
Note that I save the currently active tab in a variable, to prevent another for loop. You could also do:
document.querySelector('.active').classList.remove('active')
But I like to reduce the amount of DOM reading.
Good luck for your apprentissage, re-writing some jQuery code into Vanilla JS seems like a good method, and you might acquire a far better comprehension of JavaScript.

Generating new variables to save loop results

I´ll try to be very specific about this topic.
So I have a "for" loop in javascript working just fine. The loop aims to retrieve the URLs of all the files existing in a target folder. The question is, how can I save the retrieved URLs into individual variables?
So, in order to make things easy, I won´t paste the code I´m using, I´ll just create a simple array and run a "for" loop as an example, so you guys can tell me how you would try to save the results into new variables.
So here's the example:
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
document.write (arrayElements[index]+"<br/>");
}
So, with that code, I can "print" the different URLs included in the array (I could use console.log of course, but I´m writing in notepad++, so I have to test the code with document.write)
So the question, how can I save each URL into an individual variable?
EDIT:
Ok, so reading the first answers, I think I must clarify some things.
The question is that I need to store the URLs in variables so I can call them later. So it´s not a question about "printing" the URLs.
The function eval()
I know eval is bad
var data = ["a", "b", "c"];
function makeIndvidualVariable(array){
var size;
try{
size = array.length;
for(var i = 0 ; i < size ; ++i){
if( eval(array[i]) != undefined){
eval("var "+array[i]+"="+array[i]+";");
}else{
throw "already exist variable : "+array[i];
}
}
}catch(e){
console.log(e);
}finally{
array = size = i = null;
}
}
makeIndvidualVariable(data);
You can obtain individual variables with window object (if i got you properly).
Use the thing with JS that enables you to declare variables in window scope.
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
window['variable'+index] = arrayElements[index];
}
// now variables are available globally (through window object)
document.write(variable0); // prints FirstURL
document.write(variable2); // prints ThirdURL
// etc.
Hope this helps.
Just for the sake of printing the urls stored in array one by one and avoid loops you can use this:
document.write (arrayElements.join("<br/>"));

How do I use a for loop with localStorage to remove an item?

I try to remove specific data from localStorage and found this question.
One of the answers seems to use localStorage as an array but I don't have jQuery. To find the specific key (and value) I try to use a for loop:
localStorage.setItem("order", 1);
for(var i=0; i<localStorage.length; i++){
var item=localStorage[i];
if (item == 'order')
{
alert(item);
// I want to inspect the value...
// and then remove it
localStorage.removeItem(item);
}
}
This code never alerts and the value order is still there.
What am I missing?
localStorage is an object, you can loop through it like this
localStorage.setItem("order", 1);
for (var attr in localStorage){
if (attr == 'order') {
alert(localStorage[attr]);
localStorage.removeItem(attr);
}
}
Though there is no reason to loop, as you can simply call
localStorage.removeItem('order');
if you already know the key's name!
To remove a certain key-value-pair from localStorage, use Storage.removeItem() with the correct key:
localStorage.removeItem('order');
There is no need to loop through the items.

How to delete local storage of HTML5 by group?

I am creating localstorage dynamically like below
window.localStorage["DBname"+count]=JSON.stringify(values)
at the same time i am also creating some other local storage like
window.localStorage["login_detail"]=login_string
window.localStorage["page_config"]=page_config
so i can not use window.localStorage.clear(),because it will clear all my localstorage which i dont want, and also i can not use window.localStorage.removeItem["DBname"+count] because i count know how many "count" will come while execution.
so is there any way to delete localstorage like group delete kind of? help me out.
Simple solution
var prefix = "DBname",
continue = true,
on = 0;
while (continue) {
continue = localStorage.getItem(prefix + on)?true:false;
try { localStorage.removeItem(prefix + on); } catch (e) { continue = false; }
on += 1;
}
This will remove all local storage items beginning with DBname
Tests
Start:
DBname1
DBblah
DBnameCats
DBname 2
DBname 3
End:
DBblah
DBnameCats
An even better solution
var keys = Object.keys(localStorage),
prefix = "DBname";
for (var i = 0; i < keys.length; i += 1) {
if (keys[i].indexOf(prefix) === 0) {
localStorage.removeItem(keys[i]);
}
}
Tests
Start:
DBname1
DBblah
foobar
DBnameCats
DBname 2
DBname 3
End:
DBblah
foobar
Dealing with support
Add this one line:
Object.keys||(Object.keys=function(r){var e=[];for(var n in r)r.hasOwnProperty(n)&&e.push(n);return e});
That will let you use An even better solution on practically every browser.
I suppose you could iterate over all elements in the LocalStorage and find the keys you want to delete each individually.
A quick example would be:
function clearLocalStorageByKeyMatch(word) {
// Find items in the array where he key contains the word 'word'
var filtered = localStorage.filter(function(item, key) {
return key.indexOf(word) > -1;
});
Object.keys(filtered).forEach(function(item) {
localStorage[item] = null;
});
}
// clear localStorage where config word appear
// clearLocalStorageByKeyMatch('config');
You can also look at a library that handles that for you.
Iterating though localStorage keys/items - NO
Iterating over all the localStorage keys is not a good solution. Since localStorage could be used by other applications as well, it would be very inefficient to iterate through all items in localStorage and then remove them.
What is the best Approach
Since you are the owner of you application, you better can maintain the counts. On a rough level you can keep the "counts" you want to delete in future, may be the start and end position of count in the localStorage itself.
Once you know the start & end limit of "Count" - iterate and delete all the "DbName + Count" found in localStorage.
Another Workaround
You can have one single entity as JSON object for your application. Think of it as you are name-spacing all the localStorage items and encapsulating all of them inside one single variable.
var myApp={
"Dbname1":{},
"Dbname2":{},
"login_detail":{},
"page_config":{}
};
for saving this into localStorage:
localStorage["myApp"]=JSON.stringify(myApp);
for retrieving it back:
var myApp=JSON.parse(localStorage["myApp"]);
//now you can delete whatever db you want from `myApp` and save it back to localStorage.
This will keep other application out of danger from your code.

Changing values of each object in Javascript

What is the best way to add the additional path information to each javascript object? Like "assets/img/upload/" before each jpg name? That I have url="assets/img/upload/02.jpg" etc.? That would be great help!
My data right now:
[Object { url="02.jpg"},
Object { url="03.jpg"},
Object { url="09.jpg"},
Object { url="04.jpg"},
Object { url="5.jpg"}
...]
A simple for loop:
for(var i = 0; i < array.length; i++)
{
array[i].url = "assets/img/upload/" + array[i].url;
}
Suppose your array of objects is called MyArray:
for (var i = 0, LoopTimes = MyArray.length; i < LoopTimes; i++) {
MyArray[i].url = "assets/img/upload/" + MyArray[i].url;
}
Note that:
a) the opening curly brace goes on the same line as the for statement. See Crokfod on Javascript The Good Parts on youtube for the explanation. In javascript, putting the opening brace on the next line can create some weird bugs that are hard to detect.
b) I cache the length of MyArray in LoopTimes so that I don't have to evaluate the length of the array at every iteration.
If you are only going to be running this code in a modern browser, you could always consider using the map method of the Array object.
Assuming your array of objects is called "array"
array.map(function(item) {return item.url = "assets/img/upload/" + item.url;});
This runs the anonymous function, that takes an "item" in the array, and returns the modified url field, over each element of the array.
If you need your code to run on older browsers, stick with the for loops suggested by the other contributors.

Categories

Resources