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

I 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

creating a personalized tooltip for every item within a dynamically generated @html.dropdownfor control in mvc3

Currently, I am developing a web project using MVC 3 and Razor in C#. In my code, I have implemented @Html.DropDownListFor to dynamically display items. Now, I would like to add tooltips for each item displayed by @Html.DropDownListFor. Here is the relev ...

Utilizing URL Parameters in MEANJS

I'm currently testing my app on localhost:3000/#!/, and am encountering difficulties in retrieving URL parameters for use with Express. I have set up a new server routing file that includes the following: admin.server.routes.js 'use strict&apos ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Sending array values from a dynamic input field in Angular 4 and processing them accordingly

I am currently exploring options on how to add and delete multiple input fields. When a user submits two or more fields, I want the results to be displayed in an array. This is my HTML form: <form method="post" [formGroup]="formData"> ...

Creating a scrollable HTML5 div container with fixed divs positioned within it

I am attempting to develop an app container that mimics the functionality of Microsoft Excel. The container should scroll both horizontally and vertically, with fixed headers on the left and top that move along with the content. Here is a rough representat ...

Create a feature that allows users to dynamically add and remove image fields, with the ability to insert the selected images into a database

I'm currently using the following code and I am able to add attachments, but I'm facing an issue when trying to remove them. Can someone please help me with this problem? I tried adding an alert on the remove button and it seems to be working, h ...

Using Array.push to add an object retrieved from a Redis cache in a Node.js application is causing issues and is not functioning as expected

I've encountered a problem with retrieving all keys from my Redis cache, storing them in an array, and sending that array to the user using Express. The issue arises when I receive an empty array as the response with no objects in it. I attempted to u ...

What is the best method to choose the initial offspring of the primary brother or sister within a list item?

Is there a way to specifically target the nested li elements in my css selector? Check out the Demo li:first-child { background-color: rgb(236, 236, 236); list-style-type: none; margin-bottom: 3px; padding: 8px; } <ul> <li& ...

Please request user input in order to generate a multiplication chart

Is there a way to ensure that the program works properly so that when the user inputs a value, it is included in the multiplication table? <html> <head> <title> Multiplication Table </title> <style> body{ font-family: aria ...

Enable the expansion of a div by dragging and dropping an image onto it

Take a look at this fiddle. In this fiddle, I am able to drag and drop images onto the .drop-zone. However, I would like to enhance it so that when I drag an image onto it, the .drop-zone div expands to where I place the image. It's okay if the expand ...

Finding the Attachment ID on a JIRA Issue Page with JavaScript

Currently, I am using an ajax call that requires the attachment id in its URL. The URL is hardcoded as follows: url: AJS.contextPath()+"/rest/api/latest/attachment/10415" jQuery.ajax({ url: AJS.contextPath()+"/rest/api/latest/attachment/10415", TYPE: "GET ...

The setState method fails to properly update the state

I am currently utilizing React JS. Below is the code for my React class: class MyReactComponent extends React.Component{ constructor(props){ super(props); this.state = { passAccount: { email: "Email&quo ...

What is the best method for obtaining the HTML content of a webpage from a different domain?

I'm in the process of creating a website where I have the requirement to retrieve the HTML content of a different site that is cross-domain. Upon researching, I came across YQL. However, I don't have much experience with YQl. Is it possible to ad ...

Ways to turn off .removeClass()

Encountering an issue with jquery-2.1.4.js. Upon integrating a layerslider into my website, the script modified div classes. Attempted using older versions of the script without success. Currently have classes as follows: <a href="#" class="col-md-3 ...

Use CSS to create a fullscreen animation for an element

Is there a way to animate a div element so that it expands to fit the screen when clicked without specifying an initial position? I need the div to be able to adjust dynamically within the screen. .box { width: 80px; height: 80px; background: red; ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

Vue.js component communication issue causing rendering problems

When it comes to the Parent component, I have this snippet of code: <todo-item v-for="(todo, index) in todos" :key="todo.id" :todo="todo" :index="index"> </todo-item> This piece simply loops through the todos array, retrieves each todo obj ...

Whenever I include an onClick event to a div element, the entire webpage fails to display

Currently taking on the task of developing a seat booking website. I am encountering an issue with adding an event listener to a particular div element, which should trigger a function to store the value of the div. However, upon implementing the onClick e ...