Remove entire array from local storage - javascript

How to remove the localStorage entirely without localStorage.clear(); method?
I have a cart where you can store the products you're about to buy and the storing happens with a local storage. Currently the "Clear Cart" button works with localStorage.clear(); method, but I also have a table where you can remove single products. However, if you remove the entire table with the "remove" button on the same row and it happens to be the last product, local storage will still have an empty array and is considered as NOT null.
This is my method to remove the item:
function removeItem(itemId) {
//removes the parent row of table
$('#product-table').on('click', '.remove-item', function(e) {
$(this).closest('tr').remove();
});
var index = -1;
var obj = JSON.parse(localStorage.getItem("items")) || {}; //fetch cart from storage
var items = obj || []; //get the products
$.each(items, function(key, value) {
if (key === itemId) {
items.splice(key, 1); //remove item from array
}
});
localStorage.setItem("items", JSON.stringify(obj)); //set item back into storage
sum = 0;
$.each(items, function(key, value) {
sum += value.itemPrice;
});
$("#summary").html(sum.toFixed(2) + "€");
updateCartCount();
}
It removes items correctly, but whenever I remove the last product, the table element and add a paragraph saying "Your cart is empty. Return to shop".
Following function is below:
function hideElements() {
if ($(".cart-wrapper").length) {
if (localStorage.getItem("items") === null) {
$("#products").css("display", "none");
$("#empty").css("display", "block");
$(".btn-clear").css("display", "none");
} else {
$("#products").css("display", "block");
$("#empty").css("display", "none");
$(".btn-clear").css("display", "block");
}
}
}
The hideElements function won't recognize the local storage as empty, since it shows that there is an empty array object.
How can I achieve this by removing the entire local storage, if the removed product was the last product on the cart? I tried out with localStorage.getItems("items").length != 0 and such with no avail.
The following image displays my "empty" local storage:

What localstorage.get() returns is a string rather than JSON so what you need to do is parse string i.e. localStorage.getItem('items') returns "[]" which has length equal to 2. What you need to do is JSON.parse(localstorage.getItem('item')).length

You're probably looking for localStorage.removeItem().
Better yet, you should refactor things so there are functions solely responsible for managing the items array in your local storage:
function loadItems() {
// Returns the value of items, or an empty array.
return JSON.parse(localStorage.getItem("items") || "[]");
}
function saveItems(itemsArr) {
localStorage.setItem("items", JSON.stringify(itemsArr));
}
// Remove item with given ID (assuming each element in the array is e.g. `{id: 123}`)
const itemId = 123;
saveItems(loadItems().filter(item => item.id !== itemId));
// Update cart HTML elements:
if ($(".cart-wrapper").length) {
const haveItems = loadItems().length > 0;
$("#products").toggle(!haveItems);
$("#empty").toggle(haveItems);
$(".btn-clear").toggle(!haveItems);
}

Related

Call function if variable does not exist in a filter

I'm doing filtering on a data displayed in a view which is working correctly. I've placed a filter bar at the top of the screen where a user can filter the records. What I want to achieve is when the variable the user enters is not found in the records a function should be called
filterProducts(ev) {
this.productService.list = this.reOrderList;
const val = ev.target.value;
if (val && val.trim() !== '') {
this.productService.list = this.reOrderList.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
} else {
// value doesn't exist console.log('call another function')
}
}
Check if any items are left in the array after the filter is complete:
if (this.productService.list.length) {
// The user's query was found in the array
} else {
// The user's query was not found in the array
}

How can I check whether an item exists in localstorage or not using pure javascript

I have a project on pure javascript,and I was working on saving items to localstorage. I only need to save id, name and image of the item i am saving.
My major problem , however is i do not want save duplicate .Therefore before i save i must check whether the exists or not.
I have so far tried several approaches but all seems not to work.Below is my code snippets.
I am able to save item to localstorage with no problems, infact i can save and delete items from localstorage correctly.
const cart_DB = new cartDB();
if( cart_DB.isAddedToCart(cartInfo.id) === false) {
// save item to database
}else {
alert('item already in cart');
return false;
}
class cartDB {
/// save cart into localstorage ////
saveIntoDB(cart) {
const carts = this.getFromDB();
carts.push(cart);
// add the new array into localstorage
localStorage.setItem('carts', JSON.stringify(carts));
}
/// save cart into localstorage ///
/// return carts from storage ///
getFromDB() {
let carts;
// check from local storage
if (localStorage.getItem('carts') === null) {
carts = [];
} else {
carts = JSON.parse(localStorage.getItem('carts'))
}
return carts;
}
/// carts from storage ends ///
/// check if item already exists in database ////////
isAddedToCart(id) {
if (localStorage.getItem(id) === null
||localStorage.getItem(id).length === 0) {
return false;
}else {
return true;
}
}
//// checking items ends here ///////
}
What i want is to check whether the item exists or not before adding another item.
Assuming that you store items in array you can use below function to check if item already exists:
function checkIfItemExists (id) {
const items = localStorage.getItem('carts')
let itemExists = false
if (items) {
const itemsData = JSON.parse(items)
// check if item with given id exists in local storage data
itemExists = itemsData.find(item => item.id === id)
}
return itemExists
}
If your goal is to find out if there's a duplicate, Array.some() would be the best function you are looking for. Implement it to your function like this.
isAddedToCart(id) {
const carts = localStorage.getItem('carts');
return carts.some(cart => cart.id == id);
}
Array.some() Definition and Usage
The some() method checks if any of the elements in an array pass a
test (provided as a function).
The some() method executes the function once for each element present
in the array:
If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining
values)
Otherwise it returns false

append table data into table using loop

I want to append table data that I have saved in local storage. I have tried this loop to add in its cells and loop through changing the numbers based on the count or rows it reads. here is my JS code:
$(function() {
$("#loadTask").change(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
var rows = $('#items-table tr').length;
var loop = 0;
var r = 1;
while (loop < rows) {
$("#items-table").append('<tr>'
+'<td>'+task.cells[r][0]+'</td>'
+'<td>'+task.cells[r][1]+'</td>'
+'<td>'+task.cells[r][2]+'</td>'
+'<td>'+task.cells[r][3]+'</tr>')
r += 1;
loop += 1;
}
})
})
this obviously does not work since im guessing when I JSON.Stringify the table data it saves it into one long string becuase when I added alert(row); before and after the loop I got 1 everytime even though the task had two rows.
Here is what I use to append the data into the table which I later save in local storage using a special name so I can save multiple different table datas :
function addRow() {
var item_text = $('#item-input').val();
var item_color = $('#color-input').val();
var size_text = $('#sizes-item').val();
var any_color = $('#any-color').is(':checked') ? 'Any Color' : '';
var any_size = $('#any-size').is(':checked') ? 'Any Size' : '';
$('#items-table').append('<tr>'
+'<td>'+item_text+', '+item_color+'</td>'
+'<td>'+size_text+'</td>'
+'<td>'+any_color+', '+any_size+'</td>'
+'<td><button class="remove-btn"><div class="thex">X</div></button><td>'
+'</tr>');
}
$(function(){
$('#add-item').click(function(){
addRow();
return false;
});
$('body').on('click', '.remove-btn', function(){
$(this).parent().parent().remove();
});
});
I thought that maybe since it wont count the table rows properly the only real thing that doesnt change at any table row is the remove button that gets added with every row.
So it tried changing
var rows = $('#items-table tr').length;
to:
var rows = $('#items-table button').length;
which I thought would work but when I added the alert part before and after the loop I got 0 every time.
What could I do to be able to count each row somehow to be able to append them properly back into the table the same way they were added in.
here is the javascript that saves the table data into localStorage:
$(function() {
loadAllTasks();
$("#addTask").click(function() {
let cells = Array.prototype.map.call($("#items-table")[0].rows, row => {
return Array.prototype.map.call(row.cells, cell => cell.innerHTML);
});
// create task object from cells
var task = {
cells: cells
};
var itemCount = $("#items-table tr").length - 1;
var lengthrows = {
itemCount: itemCount
}
saveLength(lengthrows);
var rowsCount = loadLength()
alert(rowsCount);
// set name property of the task
task.Name = $("#taskName").val();
// call save method using the new task object
saveTaskInStorage(task);
});
function saveTaskInStorage(task) {
// Get stored object from localStorage
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
savedTasks = {};
// Set the new or exists task by the task name on savedTasks object
savedTasks[task.Name] = task;
// Stringify the savedTasks and store in localStorage
localStorage.setItem('tasks', JSON.stringify(savedTasks));
alert("Task has been Added");
}
function saveLength(lengthrows) {
var count = localStorage.getItem('lengthrows');
if (!count || typeof(count) !== "object")
savedCount = {};
savedCount[task.Name] = task;
localStorage.setItem('itemCount', savedTasks);
}
function loadLength(taskName) {
var lengthCount = localStorage.getItem("itemCount");
return lengthCount[taskName];
}
function loadAllTasks() {
// Get all saved tasks from storage and parse json string to javascript object
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
// To be sure that object exists on localStorage
if (!savedTasks || typeof(savedTasks) !== "object")
return;
// Get all property name of savedTasks object (here it means task names)
for (var taskName in savedTasks) {
$("#loadTask").append('<option>' + taskName + '</option>')
}
}
});
function loadTaskFromStorage1(taskName) {
var savedTasks = JSON.parse(localStorage.getItem('tasks'));
//Return the task by its name (property name on savedTasks object)
return savedTasks[taskName];
}
I am also trying to save the count of the rows in each specific task. The stuff I attempted below with the saveLength doesn't work any suggestions?
Any help is appreciated Thank You <3
Your code when you need load task might be looks like that:
$(function() {
$("#loadTask").change(function() {
var task = loadTaskFromStorage1($("#loadTask").val());
var rows = task.cells;
let tpl = (rows) => {
return rows.slice(1).map(e => '<tr>' + e.map(e => `<td>${e}</td>`) + '</tr>');
}
$("#items-table").append(tpl(rows));
})
})
For removing tasks you need to add removeTask function which i've wrote:
function removeTask (taskName) {
var tasks = JSON.parse(localStorage.getItem('tasks'));
if (typeof tasks !== "object")
return false; // our tasks list not set. return negative.
delete tasks[taskName];
$('#loadTask > option:contains(' + taskName + ')').remove();
localStorage.setItem('tasks', JSON.stringify(tasks));
return true;
};
And modify your click listener at .remove-btn. Your listener should be look like that:
$('body').on('click', '.remove-btn', function(){
$(this).parent().parent().remove();
if ($('#items-table > tbody').children().length < 2) {
console.log("attemping to remove...");
if (removeTask($("#loadTask").val()))
alert('Task successfully removed.');
}
});

using slice in angularjs array

In my angularjs app, i need to manually remove or add old/new data from a data array (service is executed in a loop). For remove, i use slice(); but there is a problem: the item is correctly removed but execVerif_distant(); is not executed for the next item. With my actual code, execVerif_distant(); is executed for each item only half a time. For example, if i need to remove entire array, only half is removed.
// start the loop, search in local datas
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
execVerif_local(itemLocalCages.url);
});
function execVerif_local(identifiant) {
var iterSearch_local = 0;
angular.forEach(responseZS, function(itemDistantCages) {
if (itemDistantCages.url == identifiant) {
iterSearch_local++;
}
});
// if we not find the local datas in distant datas
if (iterSearch_local == 0) {
// verifItem(); call
verifItem('remove', identifiant);
}
}
// verifItem();
function verifItem(action, url) {
if (action == 'remove') {
var iIndex = -1;
angular.forEach($scope.seaDocument.datas.cages, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
} else {
// do nothing
}
}
what's wrong ?
The problem is that the foreach is iterating over the same object you are removing things from. To avoid this behavior clone the object you are iterating before the loop and work with them as separate:
// ... code
var arrCopy = $scope.seaDocument.datas.cages.slice(); //this will create a deep copy.
angular.forEach(arrCopy, function(itemLocalCages) {
iIndex++;
if (itemLocalCages.url == url) {
$scope.seaDocument.datas.cages.splice(iIndex,1);
}
});
//... more code

Add and count object in cookie javascript

I'm creating Add to cart module. I have Add to cart button, when the user click on it, then it will register JSON data of the item to cookie.
This is the example of the item object:
item =
{
DepartmentID :56,
CategoryID:117,
BrandID:19,
BrandImage:" ",
BrandName:"General",
Quantity:5,
ID:706
};
This is what I have done with cookie :
$('#addToCart').click(function(){
addObjToCookie('Cart',item);
});
function serializeObjToJSON(obj) {
var json = $.toJSON(obj);
return json;
}
function deserializeJSONToObj(json) {
var obj = $.evalJSON(json);
return obj;
}
function addObjToCookie(cookieName, obj) {
var jsonObj = serializeObjToJSON(obj);
$.cookie(cookieName, jsonObj);
}
function getDataFromCookie(cookieName){
var obj = deserializeJSONToObj($.cookie(cookieName));
return obj;
}
How can I append the item object into $(cookie('Cart')) when user click on Add to cart button, with this format:
[{"DepartmentID":56,"CategoryID":117,"BrandID":19,"BrandImage":" ","BrandName":"General","Quantity":5,"ID":706},
{"DepartmentID":56,"CategoryID":117,"BrandID":19,"BrandImage":" ","BrandName":"General","Quantity":1,"ID":707}];
How to count the item in Cart cookie, in this example the result is 2.
If the item in Cart is exist, then increase Quantity + 1.
Any help would be much appreciated, thank you.
Here are tweaks to answer 1 & 2
function addObjToCookie(cookieName, obj) {
// When adding see what's in there
var currentCart = getDataFromCookie( cookieName );
// Add what's new
currentCart.push( obj );
// Save new contents
$.cookie(cookieName, serializeObjToJSON( currentCart ) );
}
function getDataFromCookie(cookieName){
var val = $.cookie(cookieName);
// Make sure this returns something valid if it's not there
if ( !val ) {
return [];
}
// No need to save off something if you're not doing anything with it
return deserializeJSONToObj( val );
}
As for #3, before actually saving the new cookie content, loop through the return value til you find a match and if you do modify that rather than pushing to the array.
If you try the loop and it doesn't work, please post your attempt. I like to help but not to write code from scratch, so you can learn some too.

Categories

Resources