How to delete an object from an array in local storage? - javascript

I'm creating a kanban board and got stuck in deleting objects from local storage. I've 3 arrays for three kanban columns and they are stored with different keys. I need to delete certain card on click and update the array in local storage.
I already can restore the items and delete the markup on click, but it's still in local storage.
Here's my working code:
var saveToStorage = function (data, key) {
var dataString = JSON.stringify(data);
localStorage.setItem(key, dataString);
};
var getFromStorage = function (key) {
var dataString = localStorage.getItem(key);
return JSON.parse(dataString);
};
var deleteFromList = function (task, list) {
for (var i in list) {
var currentTask = list[i];
if (tasksAreEqual(currentTask, task)){
list.splice(i, 1);
}
}
};
var tasksAreEqual = function (task1, task2) {
var task1Str = JSON.stringify(task1);
var task2Str = JSON.stringify(task2);
return task1Str === task2Str;
};
var createCard = function (task) {
var card = $("<div class = \"card\">");
var cardBody = $("<div class=\"card-body\">");
var cardHeader = $("<div class=\"d-flex justify-content-between align-items-start\">");
var cardText = $("<p class=\"card-text\">").text(task.message);
var btnRemove = $("<button type='button' id='remove' class='btn btn-outline-danger'>").text("x");
var btnNext = $("<button type='button' id='next' class='btn btn-outline-success'>").text("Next =>");
cardHeader.append(cardText, btnRemove);
cardBody.append(cardHeader, btnNext);
card.append(cardBody)
btnRemove.on("click", function(e) {
e.preventDefault();
card.remove();
});
$("#todo").append(card);
};
var todoList = getFromStorage("todo") || [];
var progressList = getFromStorage("progress") || [];
var doneList = getFromStorage("done") || [];
var btnAdd = $("#add-btn");
btnAdd.on("click", function () {
var taskMsg = $("#task-msg").val();
var task = {
message: taskMsg
};
createCard(task);
todoList.push(task);
saveToStorage(todoList, "todo");
});
$(function() {
var todoArr = getFromStorage("todo");
for (var i of todoArr) {
var task = i;
createCard(task);
}
});

Save the list to localStorage when task removed
// added "return list;"
var deleteFromList = function(task, list) {
for (var i in list) {
if (tasksAreEqual(list[i], task)) {
list.splice(i, 1);
}
}
return list;
};
btnRemove.on("click", function(e) {
e.preventDefault();
todoList = deleteFromList(task, todoList);
localStorage.setItem('todo', JSON.stringify(todoList))
card.remove();
});
$(function() {
var todoArr = getFromStorage("todo");
// prevent the error 'TypeError: todoArr is null'
if (!todoArr) return;
for (var i of todoArr) {
var task = i;
createCard(task);
}
});

Related

i want to make my shoppingcart local so every time i refresh the page my stuff still needs to be in there but i just dont find the right way to do it

This is my code but I don't know where to start to add localstorage.
I am really trying every website for help because I just can't find it.
var _currentArr;
var _ItemsInCart = [];
var _totalPayment = 0;
function getArticle(item, addDetails) {
var article = document.createElement("article");
var h3 = document.createElement("H3");
h3.appendChild(document.createTextNode(item.title));
article.appendChild(h3);
var figure = document.createElement("FIGURE");
var img = document.createElement('img');
img.src = 'images/'+item.img;
var figcaption = document.createElement('figcaption');
figcaption.textContent = 'Meal by: '+item.cook;
figure.appendChild(img);
figure.appendChild(figcaption);
article.appendChild(figure);
// if need details
if (addDetails) {
var dl = document.createElement("dl");
var dt1 = document.createElement("dt");
var dd1 = document.createElement("dd");
dt1.textContent = 'calories:';
dd1.textContent = item.calories;
dl.appendChild(dt1);
dl.appendChild(dd1);
var dt2 = document.createElement("dt");
var dd2 = document.createElement("dd");
dt2.textContent = 'servings:';
dd2.textContent = item.servings;
dl.appendChild(dt2);
dl.appendChild(dd2);
var dt3 = document.createElement("dt");
var dd3 = document.createElement("dd");
dt3.textContent = 'days to book in advance:';
dd3.textContent = item.book;
dl.appendChild(dt3);
dl.appendChild(dd3);
var dt4 = document.createElement("dt");
var dd4 = document.createElement("dd");
dt4.textContent = 'type:';
dd4.textContent = item.type;
dl.appendChild(dt4);
dl.appendChild(dd4);
article.appendChild(dl);
}
// info div
var div = document.createElement("DIV");
div.setAttribute("class", "info");
var p = document.createElement("P");
p.textContent = '€'+item.price+'/pp';
var a = document.createElement("A");
a.setAttribute("href", '#');
a.textContent = 'order';
a.setAttribute("id", item.id);
if (addDetails) {
a.setAttribute("data-item", JSON.stringify(item));
a.className = "order placeOrderInCart";
} else {
a.className = "order orderBtn";
}
// in div
div.appendChild(p);
div.appendChild(a);
article.appendChild(div);
return article;
}
function makeTemplateFromArray(arr) {
_currentArr = [];
_currentArr = arr;
var container = document.getElementById('dynamicContent');
container.innerHTML = '';
if (arr && arr.length) {
arr.forEach(function (item, index) {
// append article
container.appendChild(getArticle(item, false));
});
}
}
function makeTemplateFromItem(item) {
if (item) {
var container = document.getElementById('popupContentWrapper');
container.innerHTML = '';
container.appendChild(getArticle(item, true));
}
}
function showModal(id) {
// find item by id
if (_MEALS && id) {
var found = _MEALS.find(function(item) {
if (item.id === parseInt(id)) {
return true;
}
});
if (found) {
makeTemplateFromItem(found);
}
}
// open modal
document.getElementById('popup').style.display = "block";
}
// sorting
function sortItems() {
var a = _MEALS.slice(0, _MEALS.length);
var k = event.target.value;
makeTemplateFromArray(doSortData(k, a));
}
function doSortData(key, arr) {
var compare = function ( a, b) {
if ( a[key] < b[key] ){
return -1;
}
if ( a[key] > b[key] ){
return 1;
}
return 0;
};
return arr.sort( compare );
}
// change direction
function changeDirection() {
var val = event.target.value;
var a = _currentArr.slice(0, _currentArr.length);
if (val === 'desc') {
makeTemplateFromArray(a.reverse());
} else {
makeTemplateFromArray(_MEALS);
}
}
// search on input
function searchInArray() {
var val = event.target.value;
if (val && val.length > 1) {
val = val.toLowerCase();
var arr = _MEALS.filter(function (item) {
if (item.title.toLowerCase().includes(val)) {
return true;
}
});
makeTemplateFromArray(arr);
} else {
makeTemplateFromArray(_MEALS);
}
}
// prepare options
function prepareOptions(obj) {
var select = document.getElementById('sortby');
Object.keys(obj).forEach(function (key) {
var opt = document.createElement('option');
opt.value = key;
opt.innerHTML = key;
select.appendChild(opt);
});
}
// add item in cart
function addItemInCart(item) {
_ItemsInCart.push(item);
var elem = document.getElementById('cartCounter');
elem.innerHTML = _ItemsInCart.length;
}
// show cart
function showCart() {
// prepare template
var container = document.getElementById('cartItems');
var table = document.createElement("table");
var thead = document.createElement("thead");
var tbody = document.createElement("tbody");
var tfoot = document.createElement("tfoot");
container.innerHTML = '';
var thBody = '<tr><th>Meal</th><th>Price</th></tr>';
thead.innerHTML = thBody;
// tbody
_totalPayment = 0;
_ItemsInCart.forEach(function(item) {
_totalPayment += parseInt(item.price);
var tBodyTemp = '<tr><td>'+item.title+'</td><td>€ '+item.price+'</td></tr>';
tbody.innerHTML += tBodyTemp;
});
// tfoot
var tfootBody = '<tr><td>Total</td><td>€ '+_totalPayment+'</td></tr>';
tfoot.innerHTML = tfootBody;
table.appendChild(thead);
table.appendChild(tbody);
table.appendChild(tfoot);
container.appendChild(table);
// open modal
document.getElementById('cart').style.display = "block";
}
// proceed to checkout
function proceedToCheckout() {
document.getElementById('cartoverview').classList.add('hidden');
document.getElementById('personalinformation').classList.remove('hidden');
}
// validate form submit
function validatepersonalInfoForm() {
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.remove('hidden');
// set values
var val = document.querySelector('input[name="paymentmethod"]:checked').value;
document.getElementById('price').innerHTML = '€ '+_totalPayment;
document.getElementById('paymentmethod').innerHTML = 'in '+val;
}
function setRandomItem() {
var max = _MEALS.length;
var min = 0;
var number = Math.floor(Math.random() * (max - min + 1)) + min;
var item = _MEALS[number];
document.getElementById('mealofthedayimg').src = 'images/'+item.img;
}
// listen on click event for order button
document.body.addEventListener("click", function (event) {
// close modal box
if (event.target.classList.contains("close")) {
document.getElementById('cart').removeAttribute('style');
document.getElementById('popup').removeAttribute('style');
// remove classes from element
document.getElementById('cartoverview').classList.remove('hidden');
document.getElementById('personalinformation').classList.add('hidden');
document.getElementById('confirmation').classList.add('hidden');
}
// open modal box
if (event.target.classList.contains("orderBtn")) {
event.preventDefault();
showModal(event.target.getAttribute("id"));
}
// add item in cart
if (event.target.classList.contains("placeOrderInCart")) {
event.preventDefault();
var item = JSON.parse(event.target.getAttribute("data-item"));
if (item) {
addItemInCart(item);
}
}
});
setTimeout( function() {
// console.log(_MEALS);
makeTemplateFromArray(_MEALS);
prepareOptions(_MEALS[0]);
setRandomItem();
}, 100);
After you add something into _ItemsInCart, set _ItemsInCart as data in localstorage.
Before you want to get something from _ItemsInCart, get data from localstorage first and set it to _ItemsInCart.
_ItemsInCart should always sync with your data in localstorage.
How to use localstorage:
https://www.w3schools.com/html/html5_webstorage.asp
Advice: If possible, separate your DOM manipulating code with your logic code.

How do I replace todo list with a constructor function?

I watched YouTube video and completed the Todo List using Pure JavaScript. I want to change this code to constructor function. but It's not easy.
Below is the code I wrote. I want to improve this code. but it 's not clear how to fix it.
I think addItemTodo code, it's not bad. but removeItem and completeItem code is not good. I wonder if this is the best or if there are other improvements.
function TodoList(todo) {
this.todo = todo;
}
function UI() {
this.addItemTodo = function(todo) {
var list = document.getElementById('todo');
var item = document.createElement('li');
item.innerText = todo.todo;
var buttons = document.createElement('div');
buttons.classList.add('buttons');
var remove = document.createElement('button');
remove.classList.add('remove');
remove.innerHTML = removeSVG;
remove.addEventListener('click', this.removeItem);
var complete = document.createElement('button');
complete.classList.add('complete');
complete.innerHTML = completeSVG;
complete.addEventListener('click', this.completeItem);
buttons.appendChild(remove);
buttons.appendChild(complete);
item.appendChild(buttons);
list.insertBefore(item, list.childNodes[0]); // 최신 순으로 목록 삽입
};
this.removeItem = function(e) {
console.log(e.target);
var item = this.parentNode.parentNode;
var parent = item.parentNode;
parent.removeChild(item);
};
this.completeItem = function() {
var item = this.parentNode.parentNode;
var parent = item.parentNode;
var id = parent.id;
var target = (id === 'todo') ? document.getElementById('completed') : document.getElementById('todo');
parent.removeChild(item);
target.insertBefore(item, target.childNodes[0]);
};
this.clearFields = function() {
document.getElementById('item').value = "";
}
}
var addBtn = document.getElementById('add');
addBtn.addEventListener('click', function() {
var value = document.getElementById('item').value;
var todoList = new TodoList(value);
var ui = new UI();
if(value) {
ui.addItemTodo(todoList);
ui.clearFields();
} else {
console.log("리스트를 입력해 주세요")
}
});

duplicate data when searching for a specific value in javascript object

I am using the following code to look for a specific value id in javascript object. I am getting duplicate objects.
This is the javascript code I am using:
$('.seat').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
//SeatId is 1
var categoryArray = jsonData;
var id = $(this).attr('id');
var ticketData, seatLocation;
for (var i = 0; i < categoryArray.length; i++) {
var category = categoryArray[i];
for (var j = 0; j < category.assignments.length; j++) {
if (category.assignments[j].seatId == id) {
ticketData = category;
seatLocation = category.assignments[j];
}
}
}
console.log(ticketData);
console.log(seatLocation);
});
This is how the objecs look like after being parsed:
And this is how the data is being printed:
What am I doing wrong?
Try this way:
$('.seat').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var ticketData = [];
var seatLocation = [];
//SeatId is 1
var categoryArray = jsonData;
var id = $(this).attr('id');
$.each(categoryArray, function (i, cat) {
$.each(cat.assignments, function (j, ass) {
if (ass.seatId == id) {
ticketData = cat;
seatLocation = ass;
}
});
});
console.log(ticketData);
console.log(seatLocation);
});

Increment value in function

I want to increment my i value to save different value to local storage. But i always = 0, what can I do to change this behavior?
(function() {
var i = 0;
var storage = new Storage();
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set("task-"+i, ticket);
i++;
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
Declare the var i = 0 outside of the function. Right now it is being reset to 0 every time to function is run.

Incrementing key value to save data in localstorage

I need to increment key value when I'm saving data to localstorage because when I click button key is same for all records and record just update,doesn't creating new. I know I can do this with closures bit I'm fresh in JS and dont know how to do it correct.
(function() {
window.onload = function() {
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
var key = 0;
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
return key;
}());
}
}
})();
function Storage() {
this._ITEMS_DESCRIPTOR = 'items';
}
Storage.prototype.get = function() {
var fromStorage = localStorage.getItem(this._ITEMS_DESCRIPTOR);
return fromStorage ? JSON.parse(fromStorage) : [];
};
Storage.prototype.set = function(key, items) {
localStorage.setItem(key, JSON.stringify(items));
};
You need declare the variable before the function, to save the value and add 1+.
(function() {
window.onload = function() {
var key = 0; //move var key to here
document.getElementById('buttonCreate').onclick = function() {
var topicValue = document.getElementById("create-topic").value;
var statusValue = document.getElementById("create-status").value;
var descriptionValue = document.getElementById("create-description").value;
// var key = 0; remove these line
var storage = new Storage();
var ticket = {
topic: topicValue,
status: statusValue,
description: descriptionValue
};
storage.set(key, ticket);
return (function() {
key++;
return key;
}());
}
}
})();

Categories

Resources