index value cannot updated - javascript

Here I am using array to store date in local-storage. first add data that is stored after add another one the index value not increased. The newly add data only shows.
function save() {
var task = [];
localStorage.getItem('task');
task.push(document.getElementById("txt1").value);
console.log(task);
localStorage.setItem('array', task);
}

Related

Adding Items to an Empty Array with Javascript

I'm just learning Javascript and need to build a cart.
I am using a drop-down menu to select the items which are stored in another array. I then want to push the selected item to an empty array called "cart"
This is the code I'm using to select the data from the catalog array inorder to push it to the cart array:
let addFCat = document.getElementById('addfromCat');
function cat_Cart(){
// find out the index of the item loaded
let e = document.getElementById("productList");
let itemIndex = e.options[e.selectedIndex].value;
console.log(itemIndex);
// update item to cart
cart.push(catalog[itemIndex]);
localStorage.setItem("cart", JSON.stringify(cart));
// alert with updated total
// alert(`You added ${cartItems.name} to your Cart`)
}
But for some reason my cart[] remains empty.
If I manually type:
cart.push(catalog[enter index here]) in the console,
and then:
cart.length;
the cart updates.
What am I doing wrong, that it won't update my cart within the function?
(PS. I'm using the console.logs to check the code is running)
I think it is because you do refresh your browser, and it causes your cart[] to be empty, I suggest you to store the cart array in empty condition, to localStorage first, and get the updated value like this
const cart = []
localStorage.setItem("cart", JSON.stringify(cart));
function cat_Cart(){
const getCart = JSON.parse(localStorage.getItem("cart"));
// find out the index of the item loaded
let e = document.getElementById("productList");
let itemIndex = e.options[e.selectedIndex].value;
console.log(itemIndex);
// update item to cart
getCart.push(catalog[itemIndex]);
localStorage.setItem("cart", JSON.stringify(getCart));
// alert with updated total
// alert(`You added ${cartItems.name} to your Cart`)
}
local storage will help you to save any data, and it will not to be deleted even though you refresh the browser. thank you

delete specific element in an array of local storage

Currently I have datas variable that contains multiple element values.
like this
["WLP001","WLP002","WLP003","WLP004","WLP022"]
Deleting datas variable will be possible like this localStorage.removeItem("datas");
But if I have a variable in my js code like this var item = "WLP022";
and delete only the WLP022 inside of that datas would it be possible?
You can get index of item to delete then just use splice to remove that item from array and set your datas again in localStorage.
Demo Code :
var to_delete = "WLP003"
//var datas = localStorage.getItem('datas');//parse it
//suppose this is data
var datas = ["WLP001", "WLP002", "WLP003", "WLP004", "WLP022"];
var index = datas.indexOf(to_delete);//get index
datas.splice(index, 1);//remove it
console.log(datas)
localStorage.setItem('datas', JSON.stringify(datas));//set again

Delete specific string from Local Storage array

I have this code
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
let deleted = moment.splice(index, 1);
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
}
I have found the index of the element of the array that I want to delete, everything's good, but now I would like to "update" the local storage to delete the item from the index.
I can delete the specific value on the array that loads into the local Storage. Called myArray.
const myArray = map(listItems, getText);
myArray contains the "raw string data" that then gets put on the local Storage via,
localStorage.setItem('things',JSON.stringify(myArray));
How can I delete from the localStorage?
I've tried, the splice method on the local storage but doesn't work!!
Thanks!
try to parsing the moment variable to JSON
using
edit
function deleteElement() {
const myArray = map(listItems, getText);
var elementToDelete =document.getElementById('deleteElement').value;
const index = myArray.findIndex((item) => item.includes(elementToDelete));
if (index > -1) {
// delete and update local storage
console.log("found element and index ", index);
let moment = localStorage.getItem('pelis_guardades');
//try to add this code
let moment_parse = JSON.parse(moment);
let deleted = moment_parse.splice(index, 1);//edit
localStorage.setItem('pelis_guardades', JSON.stringify(deleted))
console.log(deleted);
}
before you splice the moment variable
The problem is that you've made a mistake using Array.splice.
This method mutates the given array.
You don't need the result of the splice operation. Instead you must pass the array as the new value to update the localstorage.
// 1. read value
const moment = JSON.parse(localStorage.getItem('pelis_guardades'))
// 2. mutate given array by removing one element from index.
moment.splice(index, 1);
// 3. write value
localStorage.setItem('pelis_guardades', JSON.stringify(moment))

Numerically ordered ID's of data objects in Firebase

I am pretty new to the 'game' and was wondering if it's possible to order newly added data (through a form and inputs) to the Firebase numerically so each new data entry gets the ID (number of the last added data +1).
To make it more clear, underneath you can find a screenshot of how data is currently being added right now. The datapoint 0-7 are existing (JSON imported data) and the ones with the randomly created ID belong to new entries. I would like to have the entries to comply to the numbering inside of my Firebase, because otherwise my D3 bar chart won't be visualised.
var firebaseData = new Firebase("https://assignment5.firebaseio.com");
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.push().set({games: gameName, medals: medalCount, summergames: bool});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
UPDATE:
function funct1(evt)
{
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
for (var i = 0; i < 10; i++)
{
firebaseData.child('7' + i).set({games: gameName, medals: medalCount, summergames: bool}(i)); };
Problem:
There are two ways to generate ids for your document nodes.
Calling .push() on your reference will generate that unique id.
Calling .set() on your reference will allow you to use your own
id.
Right now you're using .push().set({}), so push will generate an new id and the set will simply set the data.
// These two methods are equivalent
listRef.push().set({user_id: 'wilma', text: 'Hello'});
listRef.push({user_id: 'wilma', text: 'Hello'});
Using .set() without .push() will allow you to control your own id.
Using .push():
When managing lists of data in Firebase, it's important to use unique generated IDs since the data is updating in real time. If integer ids are being used data can be easily overwritten.
Just because you have an unique id, doesn't mean you can't query through your data by your ids. You can loop through a parent reference and get all of the child references as well.
var listRef = new Firebase('https://YOUR-FIREBASE.firebaseio.com/items');
// constructor for item
function Item(id) {
this.id = id;
};
// add the items to firebase
for (var i = 0; i < 10; i++) {
listRef.push(new Item(i));
};
// This will generate the following structure
// - items
// - LGAJlkejagae
// - id: 0
// now we can loop through all of the items
listRef.once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var name = childSnapshot.name();
var childData = childSnapshot.val();
console.log(name); // unique id
console.log(childData); // actual data
console.log(childData.id); // this is the id you're looking for
});
});
Within the childData variable you can access your data such as the id you want.
Using .set()
If you want to manage your own ids you can use set, but you need to change the child reference as you add items.
for (var i = 0; i < 10; i++) {
// Now this will create an item with the id number
// ex: https://YOUR-FIREBASE.firebaseio.com/items/1
listRef.child('/' + i).set(new Item(i));
};
// The above loop with create the following structure.
// - items
// - 0
// - id: 0
To get the data you can use the same method above to loop through all of the child items in the node.
So which one to use?
Use .push() when you don't want your data to be easily overwritten.
Use .set() when your id is really, really important to you and you don't care about your data being easily overwritten.
EDIT
The problem you're having is that you need to know the total amount of items in the list. This feature is not implemented in Firebase so you'll need to load the data and grab the number of items. I'd recommend doing this when the page loads and caching that count if you really desire to maintain that id structure. This will cause performance issues.
However, if you know what you need to index off of, or don't care to overwrite your index I wouldn't load the data from firebase.
In your case your code would look something like this:
// this variable will store all your data, try to not put it in global scope
var firebaseData = new Firebase('your-firebase-url/data');
var allData = null;
// if you don't need to load the data then just use this variable to increment
var allDataCount = 0;
// be wary since this is an async call, it may not be available for your
// function below. Look into using a deferred instead.
firebaseData.once('value', function(snapshot) {
allData = snapshot.val();
allDataCount = snapshot.numChildren(); // this is the index to increment off of
});
// assuming this is some click event that adds the data it should
function funct1(evt) {
var gameName = $('#nameInput').val();
var medalCount = $('#medalsInput').val();
var bool = $('#boolInput').is(':checked');
firebaseData.child('/' + allDataCount).set({
games: gameName,
medals: medalCount,
summergames: bool
});
allDataCount += 1; // increment since we still don't have the reference
};
For more information about managing lists in Firebase, there's a good article in the Firebase API Docs. https://www.firebase.com/docs/managing-lists.html

My Array holds previous values too every time i use.

var TransactionObject = {
arr1: [],
arr2: []
};
My Array holds previous values too every time i use my model class.
var data = update(TransactionObject.arr1);
JsonClient.send(data );
The first time the array holds some value, and the next time when i make the request... it adds the previous data too... the array is not getting cleared at all.
If you want to clear the data each time before adding new data, then somewhere your code just needs to clear the array. You could do it like this:
TransactionObject.arr1 = [];
var data = update(TransactionObject.arr1);
JsonClient.send(data );
Or, you could do it inside your update() function like this before putting data into the passed array:
var data = update(TransactionObject.arr1);
JsonClient.send(data );
function update(results) {
results = [];
// now put data into results
}

Categories

Resources