Is it possible to make changes to local storage data without impacting the rest of the data set?

https://i.sstatic.net/BBcJF.pngI am looking for a way to modify specific data in the local storage without affecting any other stored information. However, I have encountered an issue where editing values works correctly for the first three attempts, but on the fourth try, it seems to impact unrelated data within the local storage. I prefer using pure JavaScript over jQuery and I am struggling to identify where the problem lies.

let arr = new Array();

showData();

// Function to delete data from local storage
function deleteData(index) {
  arr.splice(parseInt(index), 1);
  let value = JSON.stringify(arr);
  localStorage.setItem("localData",value);

  // Display local storage data after deletion
  showData();
};

// Function to edit data in local storage
function editData(index) {

  document.getElementById("fName").value = arr[index].fName;
  document.getElementById("lName").value = arr[index].lName;
  document.getElementById("age").value = arr[index].age;
  document.getElementById("email").value = arr[index].email;
  document.getElementById("number").value = arr[index].number;

  document.getElementById("addBtn").style.display = "none";
  document.getElementById("saveBtn").style.display = "block";

  document.getElementById("saveBtn").addEventListener("click", () => {
    let localData = JSON.parse(localStorage.getItem("localData"));
    localData[index].fName = document.getElementById("fName").value;
    localData[index].lName = document.getElementById("lName").value;
    localData[index].age = document.getElementById("age").value;
    localData[index].email = document.getElementById("email").value;
    localData[index].number = document.getElementById("number").value;
    localStorage.setItem("localData", JSON.stringify(localData));
    showData();
  });
};

// Function to add data to local storage
function addData(){
  arr.push({
    fName:document.getElementById("fName").value,
    lName:document.getElementById("lName").value,
    age:document.getElementById("age").value,
    email:document.getElementById("email").value,
    number:document.getElementById("number").value,
  });
  localStorage.setItem("localData",JSON.stringify(arr));

  // Displaying the added data
  showData();

  // Clear input fields
  init();
};

// Retrieve data from local storage and display it on the screen
function showData(){
  let tbl = document.getElementById("tableDisplay");
  let str = localStorage.getItem("localData");
  let x = tbl.rows.length;

  while(--x){
    tbl.deleteRow(x);
  }
  // Check if local storage is empty
  if(str != null){
    arr = JSON.parse(str);
    for( let i=0; i<arr.length ; i++ ){
      let r = tbl.insertRow();
      r.innerHTML=`
        <td>${arr[i].fName}</td>
        <td>${arr[i].lName}</td>
        <td>${arr[i].age}</td>
        <td>${arr[i].email}</td>
        <td>${arr[i].number}</td>
        <td>
          <button type="button" class="btn btn-warning" onClick="editData(${i});"> Edit </button>
          <button type="button" class="btn btn-danger" onClick="deleteData(${i});"> Delete </button>
        </td>`;
    }
  }
  init();
};

// Define initial screen appearance
function init(){
  document.getElementById("fName").value = "";
  document.getElementById("lName").value = "";
  document.getElementById("age").value = "";
  document.getElementById("email").value = "";
  document.getElementById("number").value = "";
  document.getElementById("saveBtn").style.display = "none";
  document.getElementById("addBtn").style.display = "block";
};

// Function to clear local storage
function deleteLocalStorageData(){
  localStorage.clear();
  document.getElementById("tableDisplay").innerHTML = "All Data Deleted!";
};

document.getElementById("addBtn").addEventListener("click", addData);
document.getElementById("clearBtn").addEventListener("click", deleteLocalStorageData);

Answer №1

the issue lies in binding the saveBtn click listener multiple times here is the corrected code

var arr = new Array();
showData(); //clear data from local storage

function deleteData(index) {
  arr.splice(parseInt(index), 1);
  var value = JSON.stringify(arr);
  localStorage.setItem("localData", value); //display updated local storage data after deletion

  showData();
}

; //update data in local storage

var editIndex= null;
document.getElementById("saveBtn").addEventListener("click", function () {

    arr[editIndex].fName = document.getElementById("fName").value;
    arr[editIndex].lName = document.getElementById("lName").value;
    arr[editIndex].age = document.getElementById("age").value;
    arr[editIndex].email = document.getElementById("email").value;
    arr[editIndex].number = document.getElementById("number").value;

    localStorage.setItem("localData", JSON.stringify(arr));
    showData();
  });

function editData(index) {
  editIndex = index;
  document.getElementById("fName").value = arr[index].fName;
  document.getElementById("lName").value = arr[index].lName;
  document.getElementById("age").value = arr[index].age;
  document.getElementById("email").value = arr[index].email;
  document.getElementById("number").value = arr[index].number;
  document.getElementById("addBtn").style.display = "none";
  document.getElementById("saveBtn").style.display = "block";

}

; //add data to local storage

function addData() {
  arr.push({
    fName: document.getElementById("fName").value,
    lName: document.getElementById("lName").value,
    age: document.getElementById("age").value,
    email: document.getElementById("email").value,
    number: document.getElementById("number").value
  });
  localStorage.setItem("localData", JSON.stringify(arr)); //display added data

  showData(); //clear input fields

  init();
}

; //retrieve data from local storage and display it on the screen

function showData() {
  var tbl = document.getElementById("tableDisplay");
  var str = localStorage.getItem("localData");
  var x = tbl.rows.length;

  while (--x) {
    tbl.deleteRow(x);
  } //check if local storage is not empty

  if (str != null) {
    arr = JSON.parse(str);

    for (var i = 0; i < arr.length; i++) {
      var r = tbl.insertRow();
      r.innerHTML = "\n        <td>".concat(arr[i].fName, "</td>\n        <td>").concat(arr[i].lName, "</td>\n        <td>").concat(arr[i].age, "</td>\n        <td>").concat(arr[i].email, "</td>\n        <td>").concat(arr[i].number, "</td>\n        <td>\n          <button type=\"button\" class=\"btn btn-warning\" onClick=\"editData(").concat(i, ");\"> Edit </button>\n          <button type=\"button\" class=\"btn btn-danger\" onClick=\"deleteData(").concat(i, ");\"> Delete </button>\n        </td>");
    }
  }

  init();
}

; //define initial screen layout

function init() {
  document.getElementById("fName").value = "";
  document.getElementById("lName").value = "";
  document.getElementById("age").value = "";
  document.getElementById("email").value = "";
  document.getElementById("number").value = "";
  document.getElementById("saveBtn").style.display = "none";
  document.getElementById("addBtn").style.display = "block";
}

; //clear local storage data

function deleteLocalStorageData() {
  localStorage.clear();
  document.getElementById("tableDisplay").innerHTML = "All Data Deleted!";
}

;
document.getElementById("addBtn").addEventListener("click", addData);
document.getElementById("clearBtn").addEventListener("click", deleteLocalStorageData);

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

Customizing Image Layout with jQuery Masonry - Tips for Aligning Images

I've successfully created a jQuery masonry layout that showcases recent posts from various categories on the homepage. However, I'm facing two challenges and seeking help to address them: How do I remove the small white gaps beneath some ima ...

Is there a way to prevent this picture from shifting?

I am currently revamping the content on my work website using Joomla. I have received the old copy and now I need to enhance it. The website in question is 24x7cloud.co.uk. At the bottom of the page, I aim to include an "Accreditation's" section. Howe ...

Console displays 'undefined' when using the post method with Node.js/Express

Below is the code for my upload.ejs page: <%- include('header' ,{ title:"Playground" }) -%> <div class="wrapper"> <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="text" name="name" place ...

Retrieving URL from AJAX Request in Express JS

Currently, I am in the process of developing an Express App and encountering a challenge regarding the storage of the user's URL from which their AJAX request originated. In simpler terms, when a website, such as www.example.com, sends an HTTP request ...

Utilizing EJS to display dynamic data from a JSON file in a visually appealing D

*Excited about learning express! Currently, I have two files - index.ejs and script.js. The script I've written successfully fetches JSON data from an api. const fetch = require("node-fetch"); const url = '...' fetch (url) .then(resp ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

Tips for transforming the appearance of an asp.net page with asp:Content into a stylish css-page

Currently facing an issue where I am unable to change the background-color in my CSS file. As a workaround, I have placed the style directly within an ASP page. <asp:Content Id="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> ...

React Star Rating Component: Issue with Image Display

To all who contributed their time and effort in responding to my previous question, I offer my sincerest apologies. Initially, I had assumed that assistance wouldn't be forthcoming, so I started working on the issue myself. As a result, I have made si ...

Upload a user-sent image to a remote SFTP server for safekeeping

Can someone help me figure out how to upload a file to an SFTP remote server using ssh2-sftp-client? I am trying to retrieve the file from the user via a post request along with the destination. To process the file, I am utilizing multer. const Client = r ...

Is it possible for a CSS Transition/Transform to ease out smoothly yet not ease in at all?

It appears that the transition is smoother when I stop hovering over the button, compared to when I actually hover. Why might this be? .button_1 { border-width: 0.8px; border-color: Lightgray; background-color: hsla(209, 72%, 59%, 0.85); ...

What is the best way to access the image source attribute within a directive?

Here's a straightforward image directive example: (function () { 'use strict'; angular .module('myapp') .directive('imageTest', imageTest); function imageTest() { var directive = { ...

Issue with Image Quality in Woocommerce/Wordpress Products

I'm experiencing an issue with either Wordpress or Woocommerce. Yesterday, I updated Woocommerce while installing a new theme. Unfortunately, I'm facing a problem now where I can't seem to improve the image quality on the product page. Jus ...

Vue.js Enhances CoolLightBox with Multiple Galleries

I am trying to set up a page with multiple galleries using CoolLightBox. It worked fine for me when I had just one gallery, but now that I want to create multiple galleries - each with its own image on the page - it is only displaying one image in the ligh ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Conserving node.js native imports for Electron with rollup

I am working on a project using Electron, Svelte, and Typescript. Initially, I used a specific template from here, but it restricted access to node.js built-in imports like fs for security reasons in the browser/electron frontend. However, I do not requir ...

Leverage the power of lodash or es6 by creating a custom function that accepts an object containing deeply nested properties and outputs a new object containing only specific properties

I have a complex object with unnecessary properties and deeply nested values that I need to filter. My objective is to transform this initial object into a new object containing only the specific fields I require. Here's an illustration of the large ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

What is the best way to animate an element when it comes into the user's view

In order to activate the animation of the skill-bars when the element is displayed on the website, I am seeking a solution where scrolling down through the section triggers the animation. Although I have managed to conceptualize and implement the idea with ...

What's the best way to update the fill color of an SVG dynamically?

Is it possible to change the color of an SVG image dynamically without using inline SVG tags? I want to create a code that allows users to specify the source for the SVG tag and a hexadecimal color value, enabling them to customize any SVG image with their ...

Utilizing the Bootstrap grid system to seamlessly display images

I have been attempting to design a column that is divided into two nested columns, each containing images that should fill the entire height and width of their respective columns. However, I am facing an issue where the images are extending beyond the boun ...