Reputation: 23
I want to remove a item in an array but it doesn't get removed. I have the id of the item but I can't use it. Can you show me how I can use the id of item in tasks
array?
function appendTaskToList(val, task_id) {
$('#list').append($("<li> <a href='#' class='done-btn'>Done</a>" +
" " + val + " <a href='javascript:void(0)' class='cancel-btn'>Delete</a></li>")
.data("task", task_id));
}
if (localStorage['tasks']) {
var tasks = JSON.parse(localStorage['tasks']);
for(var i=0;i<tasks.length;i++) {
appendTaskToList(tasks[i], i);
}
}else {
var tasks = [];
}
var addTask = function(){
var val = $('#name').val();
tasks.push(val);
var task_id = tasks.indexOf(val);
localStorage["tasks"] = JSON.stringify(tasks);
appendTaskToList(val, task_id);
$('#name').val("").focus();
};
$('#add-btn').click(addTask);
$('#name').keyup(function(e){
if (e.keyCode === 13) {
addTask();
}
});
$(document).delegate('.done-btn', 'click', function() {
$(this).parent('li').addClass('done');
return false;
});
I'm stuck here:
$(document).delegate('.cancel-btn', 'click', function(e) {
var task_elem = $(e.target).closest("li");
console.log(task_elem.data());
var taks_id = task_elem.data();
$(this).parent('li').remove();
localStorage.removeItem(tasks[taks_id]);
});
Upvotes: 2
Views: 2542
Reputation: 171669
You only have one localStorage property which is "tasks"
.
The value of this property is the json you stringify.
In the line localStorage.removeItem(tasks[taks_id]);
the value of tasks[taks_id]
is not "tasks"
.
Therefore you are looking to delete something in localStorage that doesn't even exist
What you need to do is remove the item from your tasks
javascript array and then save the modified array to localStorage again.
Assuming task_id
is the index in array:
//remove from array
tasks.splice(task_id,1);
//store again
localStorage.setItem('tasks',JSON.stringify(tasks));
Upvotes: 1