0

I've been working on a tool to help people keep track of their cars in GTA, but I can't figure out how to remove them.

I've tried multiple things, but can't get it to work.

Here's my codepen https://codepen.io/Tristangre97/pen/dyoyOKw?editors=1010

function deleteItem(index) {
  var existingEntries = JSON.parse(localStorage.getItem("allCars"));
  existingEntries.splice(0, index); // delete item at index
}
2
  • Please provide a minimal reproducible example. A link to a codepen is not enough. Commented Feb 6, 2020 at 21:39
  • After deleting the item from the array you should call localstorage.setItem again to update localstorage Commented Feb 6, 2020 at 21:39

3 Answers 3

5

Splice won't update the local storage, instead, once you have removed the items you need to write the new array back to the local storage:

localStorage.setItem("allCars", existingEntries)
Sign up to request clarification or add additional context in comments.

Comments

1
function deleteItem(index) {
  const existingEntries = JSON.parse(localStorage.getItem("allCars"));
  existingEntries.splice(index, 1);
  localStorage.setItem("allCars", JSON.stringify(existingEntries));
}

The first argument in splice is the index and the second one is the length. Also, you should save the new array into the localStorage.

1 Comment

That helped, Thanks. You did accidentally add a comma instead of a period though.
0

The CodePen provided works...so I'm assuming that it was corrected as the problem was the incorrect positions of the 2 parameters of the .splice() Array method:

Original

/*
1st parameter is the index position of where within the array to start
2nd parameter is the quantity of array elements to remove
So this would always start at the beginning of the array and nth amount of elements
*/
existingEntries.splice(0, index);

Correct

/*
This will start at the specified index position and remove just that element
*/
 existingEntries.splice(index, 1);

Demo

Details are commented in demo
Note: SO Stack Snippets block Web Storage API so to review a functioning demo, see this CodePen

// Reference the <form>
const list = document.forms.gtaList;

/*
Utility functions to get/set/show localStorage data
lsGet() and lsSet() are self-explanatory
the data will be either an array of objects or an empty array
viewList() renders a <button> for each entry of the data
*/
const lsGet = key => JSON.parse(localStorage.getItem(key)) || [];
const lsSet = (key, value) => localStorage.setItem(key, JSON.stringify(value));

const viewList = data => {
  const display = list.elements.display;
  display.value = "";
  data.forEach((entry, index) => {
    display.insertAdjacentHTML(
      "beforeend",
      `<button type='button' data-idx='${index}'>
         ${entry.address} 
         --==-- 
         ${entry.car}
       </button><br>`
    );
  });
};
// Initial display of data if any in localStorage
viewList(lsGet("gtaData"));

// Register the click event to the <form>
list.onclick = autoList;

// Pass the event object (ie e)
function autoList(e) {
  // Reference all form controls of <form> (ex. input, button, select, etc)
  const gta = this.elements;
  // Get current value of <select> and <input>
  const address = gta.garage.value;
  const car = gta.auto.value;
  // Define empty object declare data
  let entry = {};
  let data;

  /*
  if the clicked tag (ie e.target) is a <button>...
  and if clicked tag id is '#add'...
  Get data from localStorage
  Assign the values of <select> and <input> to the entry object
  Add entry object to data array
  */
  /*
  ...or if the clicked tag has [data-idx] attribute...
  Get the [data-idx] value and convert it into a real Number
  Next remove() the clicked <button> from the DOM
  Get data from localStorage and splice() the object at the index
  position designated by the clicked <button> [data-idx] Number
  */
  /*
  Display data as a group of <button>s
  Finally set data to localStorage
  */
  if (e.target.tagName === "BUTTON") {
    if (e.target.id === "add") {
      data = lsGet("gtaData");
      entry.address = address;
      entry.car = car;
      data.push(entry);
    }
    if (e.target.hasAttribute('data-idx')) {
      let idx = Number(e.target.dataset.idx);
      e.target.remove();
      data = lsGet("gtaData");
      data.splice(idx, 1);
    }
    viewList(data);
    lsSet("gtaData", data);
  }
}
:root,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  font: 700 3vw/1.2 Consolas;
}

form {
  width: 90vw;
  margin: 10vh auto;
}

input,
select,
button {
  display: inline-block;
  padding: 2px 5px;
  font: inherit;
}
<form id="gtaList">
  <select id="garage">
    <option value="" selected>Select Location</option>
    <option value="Little Bighorn Ave">Little Bighorn Ave</option>
    <option value="Unit 124 Popular St">Unit 124 Popular St</option>
    <option value="1 Strawberry Ave">1 Strawberry Ave</option>
    <option value="142 Paleto Blvd">142 Paleto Blvd</option>
  </select>
  <input id="auto" placeholder="Mustang">

  <button id="add" type="button">Add</button>
  <fieldset>
    <legend>Click to Remove</legend>
    <output id="display"></output>
  </fieldset>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.