Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing and Deleting Dynamically Generated List Items in jQuery Todo List App

I'm attempting to create a todo list app in HTML, CSS, and jQuery, and I'd like to be able to add, edit, and delete tasks. I'm able to add new tasks to the list, but I'm unable to edit or delete them when I click the "Edit" and "Delete" buttons, and I'm not sure why it isn't working.

I've uploaded a copy of my code to jsfiddle (https://jsfiddle.net/LearningToCode/nndd1byt/6/) and included a copy below.

Any help you can offer would be greatly appreciated. Thanks!

Expected Behavior:

  • Clicking the "Delete" button next to a task should allow a user to delete that task.

  • Clicking the "Edit" button next to a task should allow a user to edit the text of that task.

Actual Behavior:

  • Clicking the "Delete" button does nothing.

  • Clicking the "Edit" button does nothing.

Code Examples:

HTML

<h1>Todo List</h1>  
   <input type="text" id="enter_task" placeholder="Enter Task">
   <input type="submit" id="add" value="Add Task">
<p>
   <ul id="todo_list">
   </ul>
</p>

JavaScript

function enter_task () {
   var text = $('#enter_task').val();
   $('#todo_list').append('<li>'+ text + ' <input type="submit" id="edit" value="Edit">' + '<input type="submit" class="done" id="delete" value="Delete">'  +'</li>');
};

$('#edit').click(function(){
   $('li').attr('contenteditable','true');
});

$('#delete').click(function(){
   $('li').remove();
});

$(function() {
   $('#add').on('click', enter_task);
});
like image 239
LearningToCode Avatar asked Jan 09 '23 07:01

LearningToCode


1 Answers

The problem is that your delete buttons are dynamically created. During page load, $('#delete') returns an empty set because there's no one there yet. When you finally have list items, their delete buttons are not bound to anything.

What you can do is delegate the event handler to an ancestor that exists during page load. Events "bubble" to its ancestors, making ancestors aware that you clicked a descendant. In this case, you can attach the handler to <ul>, and have it listen for clicks on .delete.

In addition, IDs are supposed to be unique. You can only have one of them on the page. Having more than one might lead to unpredictable behavior. Use classes instead.

Also, $('li') will select all <li> on the page. You might want to scope down your selection. You can remove the <li> containing your button using $(this).closest('li').remove()

The code you need should be this, plus add delete as the button class. Apply the same concept for the edit.

$('#todo_list').on('click', '.delete', function(){
  $(this).closest('li').remove()
});
like image 53
Joseph Avatar answered Jan 10 '23 21:01

Joseph