I’m trying to do a todo-list with html5 localstorage and some JavaScript/jQuery. I use an ul and store it, which works fine and I’m able to add li’s to it and they stays when I reload the page. But when trying to do a remove-function I have run into some problem.. The code below works to delete li’s after I reload the page. But I can’t remove li’s that have just been added.
when adding an item li I do like this:
$(add).click(function(e) {
if (addtext.value != ""){
$(listan).append("<li>" + addtext.value + "</li>"); //listan is my <ul>
localStorage.setItem('todo', listan.innerHTML);
addtext.value = "";
color(); //this adds some color to the li and also adds a delete-button
}
}
the color()-function:
function color(){
lin = document.getElementsByTagName('li');
for (var i = 0; i < lin.length;i++) {
if (!(lin[i].childNodes.length > 1)){
$(lin[i]).append("<input type='button' value='ta bort' class='tabort'></intput>"); //adds a deletebutton to all li's that doesnt have one
}}}
and when removing an item I do like this:
$('input[type="button"]').click(function() {
if (this.id != 'clear'){
$(this).parent().remove();
color();
localStorage.setItem('todo', listan.innerHTML);
}
});
Any ideas?
The problem is that the new items you’ve just added don’t have the click handler attached for deleting.
You have two options for handling this, one is to use
.liveinstead of.click(http://api.jquery.com/live/). The other is to wrap the delete code in a function, and call that function after adding a new item.The first option looks like this (untested):
And the second option looks like