"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestions on how to achieve this?

 
        function addTask(){
            var text = $("#new-text").val();
            if(text!=""){
                $("#todolist").append('<li><input type="checkbox" class="done" />' + text + '  <button class="delete">Remove Task</button></li>');
                $("#new-text").val('');
               
            }
           
         }
         function deleteTask(){
            if($(this).parent().css('textDecoration') == 'line-through' ) {
                $(this).parent().remove();
            }else{
                $(this).parent().remove();
            }
         }
        
         function markAsDone(){
            if($(this).parent().css('textDecoration') == 'line-through' ) {
                $(this).parent().css('textDecoration', 'none');
            }else{
                $(this).parent().css('textDecoration', 'line-through');
            }
         }
         
         $(function()  {
            $('input[type=text]').keydown(function(e){
               if(e.keyCode === 13){
                    addTask();
                }  
            });
            $("#add").on('click', addTask);
            $(document).on('click', '.delete', deleteTask);
            $(document).on('click', '.done', markAsDone);
         });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="x" class="position">To-Do List</h1>
               <div contenteditable="true">
               <ul id="todolist" class="background">
                   <li><input type="checkbox" class="done"/> Clean house <button class="delete">Remove Task</button></li>
                   <li><input type="checkbox" class="done"/>Buy milk <button class="delete">Remove Task</button></li>
               </ul>
            </div>
               <input type="text" id="new-text" /><button  id="add">Add</button>

Answer №1

If you need to iterate through the array returned by $("#todolist input:checked") and remove each element, you can use a loop to target each checked checkbox. For instance, you can achieve this with the following code snippet:

$("#todolist input:checked").each(function (index, elem) { deleteItem(elem) });
Or in your scenario, you could use deleteItem.apply(elem) since you are utilizing $(this) within your deleteItem function.

To handle the deletion of all checked items separately, you can create a new handler named deleteCheckedItems(). Your updated code might look like this:

function addListItem() {
  var text = $("#new-text").val();
  if (text != "") {
    $("#todolist").append('<li><input type="checkbox" class="done" /> ' + text + '<button class="delete">Remove Task</button></li>');
    $("#new-text").val('');
  }
}

function deleteCheckedItems() {
  $("#todolist input:checked").each(function(index, elem) {
    deleteItem.apply(elem);
  });
}

function deleteItem() {
  if ($(this).parent().css('textDecoration') == 'line-through') {
    $(this).parent().remove();
  } else {
    $(this).parent().remove();
  }
}

function finishItem() {
  if ($(this).parent().css('textDecoration') == 'line-through') {
    $(this).parent().css('textDecoration', 'none');
  } else {
    $(this).parent().css('textDecoration', 'line-through');
  }
}

$(function() {
  $('input[type=text]').keydown(function(e) {
    if (e.keyCode === 13) {
      addListItem();
    }
  });
  $("#add").on('click', addListItem);
  $(document).on('click', '.delete-checked', deleteCheckedItems);
  $(document).on('click', '.delete', deleteItem);
  $(document).on('click', '.done', finishItem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="x" class="position">To-Do List</h1>
<div contenteditable="true">
  <ul id="todolist" class="background">
    <li><input type="checkbox" class="done" /> Clean house <button class="delete">Remove Task</button></li>
    <li><input type="checkbox" class="done" /> Buy milk <button class="delete">Remove Task</button></li>
  </ul>
</div>
<button class="delete-checked">Delete All Completed</button><br/><br/>
<input type="text" id="new-text" /><button id="add">Add</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

Is it possible to combine numerous -webkit-transition animations in my css code without using keyframes?

I'm experimenting with chaining multiple -webkit-transition animations in my CSS without using keyframes. I understand it's possible to achieve this by calling a keyframe animation, but I prefer to simply overwrite the properties. However, for s ...

Is it possible to implement a Promise.some() function that includes a timeout

Scenario - collect multiple URLs and cache the responses. URLs that are processed quickly (e.g. within 500ms) are included in the current pass, while those that take longer are still cached for use in the next round (approximately 10 minutes later in our a ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Older versions of Internet Explorer, specifically IE9 and below, do not send the request body when making AJAX calls to a

I've exhausted all my options from Google trying to get this to work, but so far no luck. The issue I'm facing is making an HTTP request to a server on a different domain. It works perfectly fine on all browsers, including IE10. However, on IE ...

The excessive use of Selenium Webdriver for loops results in multiple browser windows being opened simultaneously, without allowing sufficient time for the

Is there a way to modify this code so that it doesn't open 150 browsers to google.com simultaneously? How can I make the loop wait until one browser finishes before opening another instance of google? const { Builder, By, Key, until } = require(& ...

What is the best way to streamline JSON file data by selectively extracting necessary information?

After exporting my user data from Firebase, I am looking to streamline the JSON file by filtering only the necessary fields for my data model. The format of the file obtained from Firebase is as follows: { "Users": { "00uniqueuserid3& ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...

Leverage the power of JavaScript by utilizing it as the view

Currently, in my React app, the view engine is set to hbs. There are a few hbs files in the Views folder. The following code snippet is in my app js file: // View engine app.engine( 'hbs', hbs({ extname: 'hbs', }) ) app.set ...

Close the Bootstrap modal upon clicking the "Ok" button in SweetAlert2

I need help with closing my Modal Bootstrap after clicking the Ok button in SweetAlert. I've attempted various methods, but none of them have worked so far. I'm not sure if I'm implementing it correctly, but I've utilized JQuery for thi ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

When using jsPlumb's beforeDrop function alongside ngToast, the message may not display immediately

I have been working on a project where I am integrating the jsPlumb library to create a node-based interface. jsPlumb provides an event called 'beforeDrop' which is triggered before connecting two endpoints. I plan to use this event to check a c ...

How can you create a unique record by appending a number in Javascript?

Currently, when a file already exists, I add a timestamp prefix to the filename to ensure it is unique. However, instead of using timestamps, I would like to use an ordinal suffix or simply append a number to the filename. I am considering adding an incr ...

What steps can I take to resolve the issue of item display in the dropdown menu?

My objective is to have a dropdown list with "title 1234" appearing first. When this option is selected, its value should be 1234. How can I achieve this? Here is the desired outcome: https://i.sstatic.net/CqWgn.png Currently, the list looks l ...

Conceal or reveal radio buttons according to information in a table

How can I dynamically add and remove values from a table based on radio button selections? My goal is to add the selected value to the table and hide it from the radio button list, and if the value is deleted from the table, I want to show it back in the r ...

broker handling numerous ajax requests simultaneously

Is there a way to efficiently handle multiple simultaneous ajax calls and trigger a callback only after all of them have completed? Are there any JavaScript libraries available that can manage numerous ajax calls to a database at the same time and execute ...

What is the most stylish method for merging a removeCartItem function with an addCartItem function?

Is there a way to combine these functions into a more concise and elegant piece of code? While the current setup works fine, it feels redundant to have two large functions that essentially do the same thing. const modifyCartItem = (cartItems, productToMo ...

Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]): public int retrieveLabel(Request request, Response response) throws IOException { response.header("Access-Control-Allow-Origin", "*"); ArrayList<JSONObject> orders = ...

What is the relationship between Bower and NPM when they are used together?

As a Java back-end developer transitioning to front-end JavaScript, I'm facing the challenge of setting up testing for our client-side code. While I have experience with server-side Node projects and tools like Maven, I'm relatively new to front- ...

Is there a way to change the input type=file value?

What is the best method for customizing a file upload using input type="file" in HTML? Here is an example of what I am trying to achieve: <form enctype="multipart/form-data" action="xmlupload" method="post" name="form1" id="form1"> <input type ...