Remove a specific item from localstorage with js - javascript

I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;
// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
recordCounter.innerHTML = (count = 0);
}
function addNameRecord() {
resetNotify.innerHTML = '';
var name = document.getElementById('names-field');
nameArray = JSON.parse(st.getItem('names'));
count = Number(count) + 1;
newArr = makeArr(nameArray);
// Check if there is anything in the name array.
if (nameArray != null) {
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
nameArray = [];
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}
st.setItem("names", JSON.stringify(nameArray));
name.value = '';
if (!newArr[0]) {
count = 1;
theLIst.innerHTML = nameArray;
recordCounter.innerHTML = count;
} else {
theLIst.innerHTML = newArr[0].join('');
recordCounter.innerHTML = count;
}
}
// Take our string from local storage and turn it into an array we can use
function makeArr() {
return Array.from(arguments);
}
// Purge all entries, reset counter
function clearArray() {
st.clear();
nameArray = [];
theLIst.innerHTML = '';
recordCounter.innerHTML = (count = 0);
resetNotify.innerHTML = 'Array has been purged.';
}
Heres the code I tried
// Delete a specific entry
function clearThisItem(item) {
console.log(item);
localStorage.removeItem(item);
console.log(localStorage.removeItem(item))
return item;
}

Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
After every action just update the UI using a single function call.
Note: Renamed names-field to name-field in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){
setNames([]); // initializing the empty array for first time.
}
renderData(); // display data
function addNameRecord() {
$resetMessage.innerHTML = '';
var name = document.getElementById('name-field');
addName(name.value);
renderData();
name.value = ''; //clear input field
}
function renderData(){
var names = getNames();
$resetCouter.innerText = names.length; // Count
var namesListHTML = '';
names.forEach(function(name, index){
namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
});
$list.innerHTML = namesListHTML;
}
function clearArray() {
setNames([]); // clear names
$resetMessage.innerHTML = 'Array has been purged.';
renderData();
}
function clearThisItem(name){
removeName(name); // remove from localStorage
renderData();
}
function getNames(){
namesStr = localStorage.getItem('names');
if(namesStr) {
return JSON.parse(namesStr);
}
return null;
}
function setNames(names){
return localStorage.setItem('names', JSON.stringify(names));
}
function addName(name){
var names = getNames();
names.push(name);
setNames(names);
}
function removeName(name){
var names = getNames();
var index = names.indexOf(name);
if (index > -1) {
names.splice(index, 1);
}
setNames(names);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Count : <span id="record-counter"></div></p>
<input id="name-field">
<button onclick="addNameRecord()">Add</button>
<button onclick="clearArray()">Clear</button>
<div id="list"></div>
<div id="reset-message"></div>
</body>
</html>

Use localStorage.removeItem(insertYourKeyHere); to remove an object from local storage.
For removing it from your nameArray you can search through your list for the record, set null and then sort your list by ensuring to move objects into new positions such that null is at the end, then decrement your count for the number of records

Related

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

Sum object values

I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????
Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

Parsing data from api in javascript

I am trying to parse data from a wordpress json api to my ionic app, Data from api is coming as:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
---------------
-------------
--------------
-------------
"event":["3"] this shows total number of events
}
Using javascript, how would I format the above data and save it to some variable so that I can render it easily?
events:[
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"20191015",
"date_to":"20190926",
"event":"Winter Vacation",
"description":"Winter vacation"
},
{
"date_from":"--some-data--",
"date_to":"--some-data--",
"event":"--some-data--",
"description":"--some-data--"
},
---------------
-------------
--------------
-------------
]
I tried so many methods but none are working.
I think your just should take "yourObjekt.event[0]" for a counter like:
var newObjekt = [];
for (var i=0; i<yourObjekt.event[0]; i++) {
newObjekt[i] = {
date_from: yourObjekt["event_"+i+"_date_from"][0],
date_to: yourObjekt["event_"+i+"_date_to"][0],
event: yourObjekt["event_"+i+"_event"][0],
description: yourObjekt["event_"+i+"_description"][0]
}
}
You just need to iterate over your json object. Within each iteration create a new map and push this newly created map into an array. Following is working snippet.
let data = {
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"],
"event":["3"]
}
let array = [];// Initialize an array
let index = data.event[0];// Number of events
for(let i=0;i<index;i++){
let map = {};//Initialize a new map in each iteration.
map.date_from = data["event_"+i+"_date_from"][0];
map.date_to = data["event_"+i+"_date_to"][0];
map.event = data["event_"+i+"_event"][0];
map.description = data["event_"+i+"_description"][0]
array.push(map);// finally push map into array
}
console.log(array);
Try this code, it will include all event attributes in a dynamic way
var output = [];
for(var key in datas){
// parse key
var keyParts = key.split('_');
var value = datas[key];
// ignore "event" total
if(keyParts.length > 1){
var key = keyParts.slice(2).join('_'); // generate correct key from parts
var index = keyParts[1]; // indexes : 0, 1, 2, etc.
// initialize in first call
if(output.hasOwnProperty(index) === false){
output[index] = {}
}
// append to output
output[index][key] = value
}
}
Withing 20 minutes with Googling (+ few minutes for proper adjustment of counters) ... (wrote JS few times in whole life)
I was not sure how to load it into String and did not wanted to escape whole string, so I am loading it from a text file
Input data:
{
"event_0_date_from":["20191015"],
"event_0_date_to":["20190926"],
"event_0_event":["Winter Vacation"],
"event_0_description":["Winter vacation"],
"event_1_date_from":["20190917"],
"event_1_date_to":["20190930"],
"event_1_event":["Dashain Vacation"],
"event_1_description":["--some-data--"],
"event_2_date_from":["--some-data--"],
"event_2_date_to":["--some-data--"],
"event_2_event":["--some-data--"],
"event_2_description":["--some-data--"]
}
Page and script:
<!DOCTYPE HTML>
<html>
<body>
<input type="file" id="upload">
<script>
document.getElementById('upload').addEventListener('change', readFileAsString)
function readFileAsString() {
var files = this.files;
if (files.length === 0) {
console.log('No file is selected');
return;
}
var reader = new FileReader();
reader.onload = function(event) {
//console.log('File content:', event.target.result);
var inputStr = event.target.result;
//console.log(inputStr);
var obj = JSON.parse(inputStr);
//console.log(obj);
var hasNext=true;
var counter = 0;
while(hasNext){
var properties =["date_from","date_to","event","description"];
var propertyPrefix = "event_"
var prop = propertyPrefix + counter + "_" + properties[0];
if(obj.hasOwnProperty(prop)){
console.log("element #" + counter + ": ")
for(var i = 0; i< properties.length;i++){
var propToPrint = propertyPrefix + counter + "_" + properties[i];
//console.log("loading: " + propToPrint)
console.log(" " + obj[propToPrint]);
}
counter++;
}else{
hasNext = false;
}
}
};
reader.readAsText(files[0]);
}
</script>
</body>
</html>
Result:
element #0:
20191015
20190926
Winter Vacation
Winter vacation
element #1:
20190917
20190930
Dashain Vacation
--some-data--
element #2:
--some-data--
--some-data--
--some-data--
--some-data--
So, eg. this way its possible :)

Calling multiple functions with one button

I am trying to call two functions when only the "add" button is clicked. the problem I am having is that the final four textboxes in the calculate_balances function are not outputting their variables.
var $ = function (id) {
return document.getElementById(id);
}
// Declare Arrays to store information from Inputs //
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
// Function to print results to text area //
var update_results = function () {
var list = ""; // string variable to build output //
// check to see if arrays are empty //
if (transactions[0].length == 0) {
$("results").value = "";
} else {
list = "";
// for loop to cycle through arrays and build string for textarea output //
for (var i = 0; i < transactions[0].length; i++) {
list += transactions[0][i] + " " + transactions[1][i] + " " + transactions[2][i] + "\n";
}
// display results //
$("results").value = list;
}
}
// function to gather inputs //
var add_transaction = function () {
$("add").blur();
transactions[0][transactions[0].length] = $("date").value;
transactions[1][transactions[1].length] = $("transType").value;
transactions[2][transactions[2].length] = parseFloat( $("amount").value);
update_results();
calculate_balances();
}
// function for Calculations //
var calculate_balances = function () {
var startBal = 2000.00;
var ttlDeposits = 0;
var ttlWithdrawals = 0;
var endBal = startBal;
if (transactions[1][transactions[1].length] == "deposit")
{
ttlDeposits += transactions[2][transactions[2].length];
endBal += ttlDeposits;
}
if (transactions[1][i] == "withdrawal")
{
ttlWithdrawals += transactions[2][transactions[i]];
endBal -= ttlWithdrawals;
}
$("balStart").value = parseFloat(startBal);
$("ttlDeposits").value = parseFloat(ttlDeposits);
$("ttlWithdrawals").value = parseFloat(ttlWithdrawals);
$("balEnd").value = parseFloat(endBal);
}
window.onload = function () {
$("add").onclick = add_transaction, calculate_balances;
update_results();
}
tHank you
Edit: Did not realize the OP was NOT using jQuery. Your onclick should look like this:
$("add").onclick = function(){
add_transaction();
calculate_balances();
};
The rest here is for jQuery which is not what the OP wanted.
For setting the value of a text box with jQuery use the val() method:
$("balStart").val(parseFloat(startBal));
To call the two methods when the button is clicked:
$("add").click(function(){
add_transaction();
calculate_balances();
});

Categories