How to save multiple identification numbers in localStorage with JavaScript

I am looking to implement a favorites feature on my website using HTML, CSS, JavaScript, and JSON. The JSON file is loaded through AJAX and users can search for devices to add to their favorites using sessionStorage and localStorage. However, I'm facing an issue where adding a new device overrides the existing one. I'm considering using an IF statement to check if there is already an ID present before adding a new one, but I'm unsure of how to proceed...

Here are some code samples:

$(document).on('click', '.productfavourite', function(event) { 

  // Get the ID of the clicked element as product fave
  productFave = event.target.id;

  localStorage.setItem('productFave', productFave);
  console.log(productFave);
  window.location="favourites.html";
});

Answer №1

One recommendation I have is to store the chosen items in either an object or array prior to saving it into the localStorage. Then, you can convert the object or array into a json string.

let selectedItems = [];
$(document).on('click', '.productfavourite', function(event) {
    selectedItems.push(event.target.id);
    console.log(selectedItems);
});

By following this approach, you will end up with an array that can easily be converted to json format. I hope this explanation proves useful for your needs.

Answer №2

In order to effectively manage your favorite items, it is essential to maintain a collection whether in the form of a list or dictionary. Here are some illustrative examples that can guide you through the process.

To retrieve the existing productFav from your localStorage, you can utilize the following code snippet:

var fav = localStorage.getItem("productFav") || [];

Instead of storing a single value in localStorage, aim to store the entire list by appending the new favorites to the existing ones and then serialize the updated result into a JSON string.

fav.push(newItem);

localStorage.setItem("productFav", JSON.stringify(fav));

If we assume fav represents a list, consider utilizing a dictionary if you wish to prevent the inclusion of duplicate entries.

Answer №3

If you're looking for alternatives, consider the following:

if(Storage !== "undefined") {
   localStorage.setItem("favoriteProduct", localStorage.getItem("favoriteProduct")+ ", newFaveItem3");
}

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

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Using jQuery to trigger a click event on a radio button prevents the button from being checked

Having trouble with using the .trigger("click"); function on radio buttons to activate a button in a form. When I use the code below, the button is triggered as expected. However, it seems to be interfering with the radio button, causing it to appear chec ...

How to load an iframe only upon clicking on a link

I am struggling to make the iframe popup appear only when a specific class link is clicked. Here is my HTML and JS code: Unfortunately, nothing happens when I click the link with the class 'aclass'. I have updated my JavaScript, but the issue ...

Integrating fresh components into a JSON structure

I've been attempting to insert a new element into my JSON, but I'm struggling to do it correctly. I've tried numerous approaches and am unsure of what might be causing the issue. INITIAL JSON INPUT { "UnitID":"1148", "UNIT":"202B", "Sp ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

X-ray Picker failing to retrieve a value

I am currently using the most recent version of the x-ray npm module in the code snippet below. Despite my expectations, the Meta and Metatags elements remain empty when I print out obj. Can anyone help me identify what I might be missing? var Xray = req ...

Simulating HTML5 Drag and Drop with Selenium Webdriver using JavaScript

Can someone help me convert the Python code provided below into a Javascript (nodejs) version using WebdriverIO? Here is the Python code: from selenium import webdriver with open("drag_and_drop_helper.js") as f: js = f.read() driver.execute_script(js + ...

Using Angular to retrieve JSON data from a static file

Currently, I am attempting to implement this AngularJS example from a tutorial on Login Tutorial Example. Instead of storing the username and password as simple strings, I am trying to retrieve them from a local file. I understand that this may not be the ...

Updating the ContextKey of the DynamicPopulateExtender based on the selected value from a DropDownList dynamically

I am facing an issue with my DynamicPopulateExtender control. I need it to render HTML based on the value of an asp:DropDownList. The problem lies in writing the JavaScript code that can fetch the dropdown value, assign it to the DynamicPopulate control&ap ...

AngularJS is failing to render elements stored within an array retrieved from MongoDB

My AngularJS application is not displaying the "tracking" entry from the data structure as expected. It appears as an empty array both in the HTML template and when logged to the console. The API returns the following data: [{ "_id": "57e96aaa45b09843a53 ...

Implementing react-table version 7 to display dynamic columns and rows fetched from a JSON dataset via an API

Just starting out with react and I have a json api that needs to be displayed as a table on the client side. My plan is to use react-table v7. This is my approach: Use the keys from the data as column Headers and Accessor The json data will be the rows I ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Should custom directives be utilized for templating within AngularJS applications?

Thinking about optimizing my AngularJS app, I'm considering creating custom directives for the navigation bar and footer which appear on every page. This way, I can easily modify them without having to update each individual html file. Do you think th ...

Steps to sending a request with a custom user agent

In my Angular app, I have successfully implemented server-side pre-rendering with the condition that it will only pre-render if a search bot is sending the request. Now, I need to verify if everything is pre-rendered correctly. However, when I visit my w ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

Attempting to utilize a mongo connection multiple times will result in an error message stating "Unable to use a session that

I'm encountering an obstacle while working with Mongo, here's the situation: const mongoose = require('mongoose'); const CONFIG = { host: "localhost", port: 27017, db: "dev" }; const url = `mongodb://${ ...

Node.js is known for its unreliable promise returns

Currently, I have a function in place that establishes a connection with a sql database. After querying the database and formatting the results into an HTML table, the function returns the variable html: function getData() { return new Promise((resolv ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...