简体   繁体   中英

Removing specific table Row from local storage when clicking a delete button

I am pretty new to programming (just a few weeks) and was trying to do a small practise project where you can create jokes and then have them stored in localstorage along with you name and age. There is also a garbage can to the right where you can delete the joke.

You can see the site here: https://nostalgic-poitras-17b692.netlify.app/

Here you can find the files: https://github.com/Dannus90/JavaScript_Practise_Own_Project_Unfinished

So faar you can enter everything and it detects if you have entered or not. Then the joke gets stored in local storage and displays on the screen in the table.

There are two problems at the moment: - If i click any trash can it removes all rows from local storage and I know why its doing it in the code, but I dont know how to target a specifik row and only delete that row from local storage when I click the trash can.

  • The second problem is that when I made like 2 jokes and then refreshed the page. They are still there so everything is working. However if I then after refresh type in new jokes they overwrite the old local storage instead of adding to it, so if I refresh again only the recent jokes show.

The problems should be found in the following pictures: Problem1 Problem2

This is my code so faar (In the documents from GitHub you also see the random ID generator. Took it away to decrease confusion:-)):

// Variables

const jokeInput = document.getElementById("text-1");
const nameInput = document.getElementById("text-2");
const ageInput = document.getElementById("number");
const submitBtn = document.querySelector(".btn");
const output = document.querySelector(".output-container");

// Eventlisteners
submitBtn.addEventListener("click", validateFields);

// Error
function showError(input) {
  const formControl = input;
  formControl.style.border = "3px solid red";

  removeStyle(formControl);
}

// Show Error message
function showErrorMessage(input, message) {
  input.classList.add("error");
  input.innerText = message;
  setTimeout(() => {
    input.classList.remove("error");
  }, 3000);
}

// Show success
function showSuccess() {
  jokeInput.style.border = "3px solid green";
  nameInput.style.border = "3px solid green";
  ageInput.style.border = "3px solid green";

  const small = document.querySelector(".small-3");

  small.classList.add("success");
  small.innerText = "You have successfully entered all fields";
  setTimeout(() => {
    small.classList.remove("success");
  }, 3000);

  removeStyle(jokeInput, nameInput, ageInput);
}

// Remove Style
function removeStyle(input, input2, input3) {
  setTimeout(() => {
    input.style.removeProperty("border");
    input2.style.removeProperty("border");
    input3.style.removeProperty("border");
  }, 3000);
}

// Main Function
function validateFields(e) {
  e.preventDefault();

  if (jokeInput.value === "") {
    showError(jokeInput);
    const small = document.querySelector(".small-1");
    showErrorMessage(small, "Please provide a joke");
  }

  if (nameInput.value === "") {
    showError(nameInput);
    const small = document.querySelector(".small-2");
    showErrorMessage(
      small,
      "Please fill in your name with alpabetical characters only"
    );
  }

  if (ageInput.value === "") {
    showError(ageInput);
    const small = document.querySelector(".small-3");
    showErrorMessage(small, "Please enter your age");
  }

  if (
    jokeInput.value !== "" &&
    nameInput.value !== "" &&
    ageInput.value !== ""
  ) {
    showSuccess();
    updateDOM(jokeInput.value, nameInput.value, ageInput.value);
  }
}

// Save DOM Data
let savedLocalStorage1 = [];
let savedLocalStorage2 = [];
let savedLocalStorage3 = [];
let savedLocalStorage4 = [];

// Update local storage

function updateLocalStorage() {
  localStorage.setItem(
    "savedLocalStorage1",
    JSON.stringify(savedLocalStorage1)
  );
  localStorage.setItem(
    "savedLocalStorage2",
    JSON.stringify(savedLocalStorage2)
  );
  localStorage.setItem(
    "savedLocalStorage3",
    JSON.stringify(savedLocalStorage3)
  );
  localStorage.setItem(
    "savedLocalStorage4",
    JSON.stringify(savedLocalStorage4)
  );
}

// Update DOM
function updateDOM(input1, input2, input3) {
  const outputContainer = document.querySelector(".output-container");

  const row = outputContainer.insertRow(1);
  const cell1 = row.insertCell(0);
  const cell2 = row.insertCell(1);
  const cell3 = row.insertCell(2);
  const cell4 = row.insertCell(3);

  cell1.innerHTML = `${input1}`;
  cell2.innerHTML = `${input2}`;
  cell3.innerHTML = `${input3}`;
  cell4.innerHTML = `<i class="fas fa-trash-alt id4"></i>`;

  savedLocalStorage1.push({ id: uuidv4(), cell_1: `${input1}` });
  savedLocalStorage2.push({ id: uuidv4(), cell_2: `${input2}` });
  savedLocalStorage3.push({ id: uuidv4(), cell_3: `${input3}` });
  savedLocalStorage4.push({
    id: uuidv4(),
    cell_4: `<i class="fas fa-trash-alt id4"></i>`,
  });

  updateLocalStorage();

  const rows = document.querySelectorAll("tr");
  if (rows.length > 2) {
    resetBounce();
  }
}

window.onload = (e) => {
  function DOMOutput() {
    const sto1 = JSON.parse(localStorage.getItem("savedLocalStorage1"));
    const sto2 = JSON.parse(localStorage.getItem("savedLocalStorage2"));
    const sto3 = JSON.parse(localStorage.getItem("savedLocalStorage3"));
    const sto4 = JSON.parse(localStorage.getItem("savedLocalStorage4"));

    const outputContainer = document.querySelector(".output-container");

    for (let i = 0; i < sto1.length; i++) {
      const row = outputContainer.insertRow(1);

      const cell1 = row.insertCell(0);
      cell1.innerHTML = sto1[i].cell_1;

      const cell2 = row.insertCell(1);
      cell2.innerHTML = sto2[i].cell_2;

      const cell3 = row.insertCell(2);
      cell3.innerHTML = sto3[i].cell_3;

      const cell4 = row.insertCell(3);
      cell4.innerHTML = sto4[i].cell_4;

    }
  }

  DOMOutput();
};

// Delete from local Storage

// Reset bounce function
function resetBounce() {
  setTimeout(() => {
    const cell4 = document.querySelectorAll(".fas");
    cell4.forEach((element) => element.classList.remove("fas", "fa-trash-alt"));
  }, 50);

  setTimeout(() => {
    const cell4 = document.querySelectorAll(".id4");
    console.log(cell4);
    cell4.forEach((element) => element.classList.add("fas", "fa-trash-alt"));
  }, 75);
}

// Delete Function
output.addEventListener("click", function clearRow(e) {
  if (e.target.className.includes("fas")) {
    e.target.parentElement.parentElement.remove();

    // Needs to be fixed!

    localStorage.removeItem("savedLocalStorage1");
    localStorage.removeItem("savedLocalStorage2");
    localStorage.removeItem("savedLocalStorage3");
    localStorage.removeItem("savedLocalStorage4");
  }
});

Your problem - as you have correctly realized - is that you delete the whole item. But what you need to do instead, is copy over the contents from the old input and add the new on top of it.

First step would be to declare let sto1, sto2, sto3, sto4; as global variables, so that every one of your functions always have access to it. You populate these variables in your onload function, basically the same way you did before, you only have to remove the const keyword in front of them.

When you add a new item to the local storage, you access the global stored variable and use the spread operator to add all the old items to the newly created array:

 savedLocalStorage1 = [...sto1, { id: uuidv4(), cell_1: `${input1}` }];
  savedLocalStorage2 = [...sto2, { id: uuidv4(), cell_2: `${input2}` }];
  savedLocalStorage3 = [...sto3, { id: uuidv4(), cell_3: `${input3}` }];
  savedLocalStorage4 = [
    ...sto4,
    {
      id: uuidv4(),
      cell_4: `<i class="fas fa-trash-alt id4"></i>`
    }
  ];

For removing an item, you basically do the same, but you have to remove the item you do no longer need, maybe with a filter function (do this alone for practice, ask if you need a hint).

Thanks for help!

It did not work completely but it gave me the right idea of what to do. I first set the sto to global variables as you said but I could not use the spread on savedLocalStorage it gave me the following message: enter image description here

The garbage cans also started to jump out of sync.

Not sure why it did not work as intended because I think the solution looked good. Maybe the length of savedLocalStorage could not be null as of first when I only stored it in sto1, sto2, sto3, sto4 on window load.

I used the spread operator down here instead and then it seemed to work(also initialized sto1-2-3-4 as empty arrays also - that might have been a problem also): Working

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM