Skip to main content

Interactive Task List having Add/Remove Functions

By SamK
0
0 recommends
Interactive-Task-List-having-Add-Remove-Functions

In this tutorial, you will learn how to create an interactive task list having add/remove functions, as shown here.

Interactive Task List Demo

HTML

<!-- Heading for the task list application -->
<h2>Interactive Task List</h2>

<!-- Label for the input field -->
<label>Enter a new task</label>

<!-- Input field for entering a new task -->
<input type="text" id="todo-input">

<!-- Button to add a new task to the list -->
<button id="add-todo">Add Task</button>

<!-- Unordered list where the tasks will be displayed -->
<ul class="todo-list" id="todo-list">
  <!-- Task items will be dynamically appended here -->
</ul>

<!-- Including the jQuery library for easier DOM manipulation and event handling -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

jQuery

$(document).ready(function() {
  // Wait until the DOM is fully loaded

  // Event listener for the "Add Task" button
  $('#add-todo').click(function() { 
    // Get the value entered in the input field
    var newTask = $('#todo-input').val(); 

    // Check if the input field is not empty
    if (newTask) {
      // Add a new list item (task) to the unordered list
      // Each task includes the entered text and a "Remove" button
      $('#todo-list').append('<li class="todo-item">' + newTask + ' <button class="remove">Remove</button></li>');

      // Clear the input field after adding the task
      $('#todo-input').val('');
    }
  });

  // Event listener for dynamically added "Remove" buttons
  $('#todo-list').on('click', '.remove', function() { 
    // Remove the parent list item (task) when the "Remove" button is clicked
    $(this).parent('.todo-item').remove();
  });
});
Category(s)
Topic(s)