Deleting an element from an array stored in local storage with the help of jQuery

Summary: Developing a front-end wish list feature

Tech Stack: Utilizing HTML5 (localStorage), CSS, and jQuery

Key Features: Ability to add and delete items dynamically with real-time count display

Challenge: Issue encountered when trying to remove added product after reloading the page.

Code Block with Problematic Section:

$("#wish_list_item").on("click", ".w-premove", function() {
$product_id = $(this).attr("wpid");
$("#list_id_" + $product_id).remove();
wish_list = $.grep(wish_list, function(n, i) {
  return n != $product_id;
});
localStorage.setItem(wishlistkey, JSON.stringify(wish_list));
show_message("Product removed");
count_items_in_wishlist_update();
});
});

Visit my Fiddle for demonstration: https://jsfiddle.net/3ybwf3c3/4/

Solution Method: Follow this link for the updated solution: https://jsfiddle.net/3ybwf3c3/6/

Included Code Snippet:

$("tr.wishlist-item").each(function(index, el) { 
    wish_list.push(el.outerHTML);
});

Answer №1

The problem lies in this section of the code:

wish_list = $.grep(wish_list, function (n, i) {
    return n != $product_id;
});

Here, the variable n contains the HTML content for an entire tr element, while $product_id is simply a string ID. As a result, every element matches and all rows are placed back into local storage.

Instead of doing that, you can directly retrieve the new HTML strings by querying the DOM again after removing the product:

wish_list = [];

$("tr.wishlist-item").each(function(index, el) { 
    wish_list.push(el.outerHTML);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Are there any thoughts on how to troubleshoot display problems specifically on mobile

Whenever I use Safari on iOS for my web application, I encounter strange rendering issues. It's odd because the majority of the time everything functions as it should, but every now and then these bugs crop up with no discernible pattern. Examples th ...

Responsive menu not collapsing properly and appearing funky in Drupal

I've managed to create a responsive navigation bar, but I'm encountering two issues. Firstly, when I resize the screen on my test pages, not all of the links hide as expected. Secondly, after inserting the code into Drupal, the nested links appea ...

Move the button text back to its original position with animation

I have a button with text that shifts to the right by 15px when hovered over. However, when the cursor is removed, the text immediately snaps back instead of smoothly transitioning back to its original position. I tried setting the ease-in-out property but ...

Bundling sub-components using Rollup for NodeJS application packaging

My ES6 library consists of several sub-modules arranged like this: - package.json - lib - my_package - file1.js - file2.js - sub_module1 - file3.js - file4.js Currently, I import modules within my package using file resolution r ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

What is preventing BODY from respecting min-height: 100% ?

Struggling to create a basic webpage with a container that extends to the bottom? Here's what I'm aiming for: #Main should be as tall as the viewport, but able to stretch further with additional content. body should match the viewport height, y ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

The call signatures for `node-fetch -- typeof import("[...]/node-fetch/index")'` are not properly defined

Originated from this source: https://github.com/node-fetch/node-fetch#json ... my personal code: const fetch = require('node-fetch'); async function doFetch() { const response = await fetch('https://api.github.com/users/github'); ...

When adjusting to mobile dimensions, the responsive website design struggles to center the navbar properly

I am currently developing my senior year portfolio website and I am struggling to center the navbar (Work About Contact) when it is in mobile mode. My goal is for it to be positioned directly below the logo, perfectly centered, but so far nothing I have tr ...

Alerts are essential for the proper functioning of the AJAX function. Without them

As I incorporate a substantial amount of AJAX with XML Http Requests on my website, I encounter a peculiar issue with a few random AJAX calls. There seems to be an execution problem within my JavaScript code in the onreadystatechange function where certain ...

Moving draggable items out of a div and placing them into a designated droppable area

I'm facing an issue with dynamically creating draggable "divs" within a "table" and trying to make them drop into multiple droppable areas. The problem is that when I drag the element, it leaves a gap and upon dropping, it lands in multiple places ins ...

Tips for aligning multiline text in the center of images with varying widths

Excuse my lack of experience, but I have a question, I am looking to center a header and some text next to an image with variable width. Additionally, the text should be able to position on either side of the image, while still being coded first in the HT ...

What are the benefits of declaring variables with JSON in a JavaScript file instead of simply reading JSON data?

Lately, I've been delving into the world of leaflets and exploring various plugins. Some of the plugins I've come across (like Leaflet.markercluster) utilize JSON to map out points. However, instead of directly using the JSON stream or a JSON fi ...

Generating hierarchical structures from div elements

Looking for guidance on how to parse a HTML page like the one below and create a hierarchical Javascript object or JSON. Any assistance would be much appreciated. <div class="t"> <div> <div class="c"> <input t ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...

design facebook type box scroll bar

After extensively searching through various stackoverflow answers in an attempt to change the CSS for a Facebook likebox scrollbar, I have had no success. Below is the code that I am currently using: <div id="fb-root"></div> <script>(fun ...

Tips for incorporating a Font Awesome icon <i> within a select dropdown and customizing its appearance

I am facing an issue while trying to insert an icon into a select option. The error message I received is: Warning: validateDOMNesting(...): cannot appear as a child of <option> To indicate that certain fields are required, I am using asterisk ic ...

Disregard Cloudflare's Automatic RocketLoader feature for certain JavaScript scripts

After extensive research and failed attempts, I am seeking help to disable Cloudflare Rocketloader for a specific JavaScript file on my WordPress website. Specifically, I need to exclude the Automatic Rocket Loader for a particular .js file. I attempted t ...