localStorage - Delete local|Storage value based on key - javascript

I am facing some problem in deleting localStorage json data. I have passed data in JSON format and want to delete value based on ID on click event. For example in JSON array if I have three entries of same id then want to delete three at a time.
here is my code
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var feed = {"proid":"2","canvas":"abc"};
a = JSON.parse(localStorage.getItem('names')) || [];
names = JSON.stringify(feed);
a.push(names);
localStorage.setItem('names', JSON.stringify(a));
var obj = "["+a+"]";
localStorage.setItem("productidf", obj);
$('#delete-item').click(function(){
var jsonprodId = localStorage.getItem("productidf");
var parsedJSON = $.parseJSON(jsonprodId);
var id = 2;
for(var i = 0; i < parsedJSON.length; i++){
if(parsedJSON[i].proid == id){
localStorage.removeItem(parsedJSON[i]);
}
}
localStorage.setItem("productidf", JSON.stringify(parsedJSON));
var newss = localStorage.getItem("productidf");
console.log(newss);
});
});
</script>
<a class="clicks" id="delete-item">Delete Items</a>
This code is not working to remove all values of id from localStorage. I can't use localStorage.clear(). Because it clear all localstorage.

Your localStorage.removeItem(parsedJSON[i]); line was the culprit.
localstorage cannot be traversed like an array. It just stores data in string format.
So you need to filter parsedJSON array using a js filter and then store the result back in localStorage
<script type="text/javascript" src="http://code.jquery.com/jquery-
latest.min.js"></script>
<script type="text/javascript">
var feed = {"proid":"2","canvas":"abc"};
var feed2={"proid":"3","canvas":"jack"}
a = JSON.parse(localStorage.getItem('names')) || [];
a.push(feed);
a.push(feed2);
localStorage.setItem('names', JSON.stringify(a));
localStorage.setItem("productidf", JSON.stringify(a));
var jsonprodId = localStorage.getItem("productidf");
var parsedJSON = $.parseJSON(jsonprodId);
var id = 2;
parsedJSON=parsedJSON.filter((obj)=>{
return obj.proid != id;
})
debugger
var obj = JSON.stringify(parsedJSON);
localStorage.setItem("productidf", obj);
console.log(parsedJSON);
</script>

Related

Save multiple inputs to localStorage

I'm trying to save multiple inputs to localStorage. I used a 'for' loop for this purpose, but it saved the same value for all three inputs. I want the separate foreach values, not all of them at once:
<script>
document.addEventListener('DOMContentLoaded', function() {
var j = document.getElementsByName('emploi').length;
var i;
for(i=0; i<=j; i++) {
var x = document.getElementsByName('emploi')[i];
x.value = localStorage['emploi'];
x.onchange = function() {
localStorage['emploi'] = this.value;
}
}
});
</script>
<!--Html-->
<!--SALE-->
<input type="text" name='emploi' placeholder='Sale'>
<!--les prof-->
<input type="text" name='emploi' placeholder='Professeur'>
<!--les classes-->
<input type="text" name='emploi' placeholder='Class'>
Store a JSON.stringified object instead of a simple string value otherwise you are using the same value for all 3
document.addEventListener('DOMContentLoaded', function() {
// parse stored JSON if it exists otherwise an empty object
var values = JSON.parse(localStorage.getItem('emploi') || '{}');
var inputs = document.getElementsByName('emploi');
for (let i = 0; i < inputs.length; i++) {
var x = inputs[i];
x.value = values[i] || '';// stored value if it exists or empty string
x.onchange = function() {
// assign value to the object above
values[i] = this.value;
// store updated version of object
localStorage.setItem('emploi', JSON.stringify(values));
}
}
});
It seems that your main issue is knowing how to save data to localStorage. You need to rewrite your code based on the syntax below.
Syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");
Syntax for READING data from localStorage:
const lastname = localStorage.getItem("key");
Syntax for REMOVING data from localStorage:
localStorage.removeItem("key");

Cannot read property 'push' of undefined How to solve?

var item_data = [];
var index = 0;
var data = JSON.parse([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data[index].push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Anyone can please help me why it appearing script error in my system it appearing
Uncaught TypeError: item_data[index].push is not a function
How can I solve this issue?
Use assignment operator (=) to insert any item at specific position of an array by using index like:
item_data[index] = data;
OR: If you want to use push() you do not need to use index at all. Because
The push() method adds one or more elements to the end of an array and returns the new length of the array.
item_data.push(data);
var item_data = [];
var index = 0;
var data = JSON.parse('[{"A":"0","B":"100","C":"0","D":"0"}]');
item_data[index] = data;
console.log(item_data);
Change the JSON to string and push that into the array item_data.
var item_data = [];
var index = 0;
var data = JSON.stringify([{"A":"0","B":"100","C":"0","D":"0"}]);
item_data.push(data);
console.log(item_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Push/update array from JavaScript to HTML

I have made a array of data from Firebase, and want to display it on my website. It works fine one time, but when Firebase is updated, the website doesn´t update correspondingly.
My goal is to make a list of updates. So when the database is updated, the new update is shown above the previous.
console.log(arr); logs every change made in the database, so basically I want what the console displays..
JS code:
firebase.initializeApp(config);
database = firebase.database();
var ref = database.ref("users");
ref.on("value", gotData, errData);
function gotData(data) {
// console.log(data.val);
var users = data.val();
var keys = Object.keys(users);
//console.log(keys);
for (var i = 0; i < keys.length; i++) {
var k = keys [i];
var name = users [k].Name;
var gender = users [k].Gender;
var car = users [k].Car;
var location = users [k].Location;
var destination = users [k].Destination;
// initialize array
var arr = [
name,
gender,
car,
location,
destination,
];
// append new value to the array
arr.push(destination);
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
}
function errData(err) {
console.log("Error");
console.log(err);
}
<!DOCTYPE html
<html>
<head
<meta charset="utf-8">
<title>Test</title>
<script src="https://www.gstatic.com/firebasejs/live/3.1/firebase.js"></script>
</head>
<body>
Test
<!-- Value -->
<ol id="B1"></ol>
<script src ="App.js"></script>
</body>
</html>
Firebasestructure:
App
users
09IEbFijEnQpDita5DyhUdBE0eD3
Name: "Nick"
Car: "Audi"
Gender: " Male"
Location: "Home"
Destination: " Beach"
Is there a good (and hopefully not to complicated) way to reach my goal?
Thank you.
You are resetting your array in every iteration, while you really want to keep the data from the previous iterations in there. So intitialise your array before entering the loop, and only add to it within the loop. In the same way you overwrite the output in the HTML element in each iteration. Instead, accumulate the data in the loop and only output the array after the loop:
function gotData(data) {
var users = data.val();
var keys = Object.keys(users);
// initialize array here
var arr = [];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var name = users[k].Name;
var gender = users[k].Gender;
var car = users[k].Car;
var location = users[k].Location;
var destination = users[k].Destination;
// append new value to the array
arr.push([
name,
gender,
car,
location,
destination,
]);
}
// And now output:
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
All this can be done a bit shorter with the use of Object.values (assuming you want all the data fields):
function gotData(data) {
var arr = Object.values(data.val()).map(Object.values);
document.getElementById('B1').innerHTML = JSON.stringify(arr);
console.log(arr);
}
If you want the last value at the top of the output then use the reverse method, and if you want it in a list format then map the values to li tags. Finally, you may want to limit the number of rows to some constant (e.g. 10), which you can do with slice:
function gotData(data) {
var arr = Object.values(data.val()).map(Object.values);
B1.innerHTML = arr.slice(-10).reverse().map(val => `<li>${val}</li>`).join('');
}
Note that you don't really need document.getElementById nowadays, since browsers declare global variables for each of the elements with an id attribute. So you can just use the B1 variable.

How can i use script parameters into my js file?

I have this script code:
<script src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
How can i get the values of q(123)and parameter1(450) and parameter2(300) and use them into embed.js file? I want to make conditions into my embed.js by using these values. How can i achieve that?
Give the script element and ID attribute like this:
<script id="embed-script" src="http://example.com/embed.js?q=123&parameter1=450&parameter2=300"></script>
Javascript:
var url = document.getElementById('embed-script');
function parseGet(val) {
var result = "",
tmp = [];
var items = url.src.split("?")[1].split('&');
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === val)
result = decodeURIComponent(tmp[1]);
}
return result;
}
Get the values like this, in embed.js:
var value1 = parseGet('q');
value1 should then be "123".
I think you can't,but you can declare all param before required your js file same as:
<script type="text/javascript">
var q = 123;
var parameter1 = 450;
var parameter2 = 300;
</script>
<script src="http://example.com/embed.js"></script>
You could place the parameters in attributes of the <script> tag.
<script src="http://example.com/embed.js" q="123" parameter1="450" parameter2="300"></script>
You can access these parameters in embed.js with
document.currentScript.getAttribute('q');
document.currentScript.getAttribute('parameter1');
document.currentScript.getAttribute('parameter2');
Note: document.currentScriptdoes not work on IE.
For more info check this out.
You can access script tag as the last script tag if ask for it without waiting for document load.
~function() {
var s = document.querySelectorAll("script");
s = s[s.length-1];
console.log(s.src);
}();

jquery saving data in array

I want to save and add on every click data to an array. I tried this
var data = [];
var save = [];
s=0;
i=0;
some called function(){
data[i++] = some result;
data[i++] = some other result;
}
$('#someelement').click(function(){
save[s++] = data;
console.log(save); // for debugging
i = 0;
data = '';
});
The first save works, but after that I just empty arrays added. Any pointers ?
It's because you're replacing the Array with a string.
data = '';
You should replace it with a new Array instead.
data = [];
Or reuse the data Array by adding a shallow copy of data to save, then clearing data.
save[s++] = data.slice();
data.length = i = 0;
This allows any other code that has a reference to data to retain its reference so that it is always viewing the data that is being updated.
You might want to try making a copy of the data array:
save[s++] = data.slice(0);
This way, whatever happens to data array wont affect the save array's items.
You can use this:
data[data.length] = <some value>;
If you're trying to add the current contents of data to a single element in save, use Array.push:
$('#someelement').click(function(){
save.push(data);
console.log(save); // for debugging
i = 0;
data = [];
});
...or if it's that you want the current values in data added to save, use Array.concat, resetting data back to an empty array:
$('#someelement').click(function(){
save = save.concat(data);
console.log(save); // for debugging
data = [];
});
You should use [] to create new array.
Here is working example:
<script>
var data = [];
var save = [];
s=0;
i=0;
function addRes(){
data[i++] = 'some result';
data[i++] = 'some other result';
}
$('#someelement').click(function(){
addRes();
save[s++] = data;
console.log(save); // for debugging
i = 0;
data = [];
});
</script>

Categories

Resources