0

I have an array saved in localstorage and trying to delete an element onclick based on input value. I have the code below but I cant make it work. Please help, Thanks in advance :)

var datarray = [];

function deldata() {

  // retrieve stored data (JSON stringified) and convert
  var storedData = localStorage.getItem("list_data_key");
  if (storedData) {
    datarray = JSON.parse(storedData);
  }


var titleValue = document.getElementById('listxt').value;
// Find and remove item from an array
var i = array.indexOf(titleValue);
if(i != -1) {
    array.splice(i, 1);
}
localStorage.setItem("list_data_key", JSON.stringify(datarray));
  datapost();
}

jsfiddle

1
  • you're not using function deldata...? And you're using JSON.stringify(datarray) but changing data. Please rethink your question and try again Commented Sep 22, 2017 at 17:33

2 Answers 2

1

Watch your variable names.

function deldata() {
  // retrieve stored data (JSON stringified) and convert
  var storedData = localStorage.getItem("list_data_key");
  if (storedData) {
    datarray = JSON.parse(storedData);
  }

  var titleValue = document.getElementById('listxt').value;
  // Find and remove item from an array
  var i = datarray.indexOf(titleValue);  //  HERE  (was 'array')
  if(i != -1) {
    datarray.splice(i, 1);  //  HERE  (was 'array')
  }
  localStorage.setItem("list_data_key", JSON.stringify(datarray));
  datapost();
}
Sign up to request clarification or add additional context in comments.

Comments

0

Change

var i = array.indexOf(titleValue);
if(i > -1) {
    array.splice(i, 1);
}

to

var i = datarray.indexOf(titleValue);
if(i > -1) {
    datarray.splice(i, 1);
}

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.