"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

I'm curious as to why the web browser is showing a timestamp below the image I have on my HTML page

Issue at Hand: I am currently working on coding a website that involves displaying an image. However, when the image is loaded, a timestamp appears underneath it in the web browser. Query: Could you please shed some light on why a timestamp is showing up ...

Exploring AngularJS: Retrieving a list of filenames from a specified directory

In the public directory of my application, there is a folder named 'x'. I have the path name to the folder (/path/to/dir/x) but I am unsure of the names of the files within it. How can I retrieve the file names and provide URL links to them in an ...

Leverage the Power of Multiple Markers on Google Maps with API Integration

My project involves creating a WordPress site that displays one marker on a map and has a list of additional locations below it. I aim to remove the description under the map and replace it with a simple list of locations alongside markers on the map. ...

Exploring the world of data manipulation in AngularJS

Seeking to comprehend the rationale behind it, I will share some general code snippets: 1) Fetching data from a JSON file using the "loadData" service: return { myData: function(){ return $http.get(path + "data.json"); } } 2) ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Adjust the fade-in effect to transition from a white hue to a custom color

Is there a way to customize the color of the fadeIn() effect from its default white to a specific color? For example, when transitioning the entire webpage fades in from grey and fades out to grey when a link is clicked. Here is my current code snippet: ...

What methods can be used to maintain the selected date when the month or year is changed in the react-datepicker component of reactjs?

At the moment, I am using the Month selector and Year selector for Date of Birth in the react-datepicker component within a guest details form. The current functionality is such that the selected date is highlighted on the calendar, which works fine. How ...

MUI: reveal multiple selection when hovering & prevent dropdown from moving around

Utilizing material ui, I am facing two issues with a multiple select component that I cannot seem to resolve: While selecting an item, the dropdown moves around (I have already attempted solutions like MenuProps={{ variant: "menu", getContentAnc ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

Is there a way to deactivate the dot key using the keyup event in Vue.js 2?

My current approach is as follows: <template> ... <input type="number" class="form-control" v-model="quantity" min="1" v-on:keyup="disableDot"> ... </template> <script> export default{ ... methods:{ ...

The FaceDetector within the expo application continues to activate the "onFacesDetected" event in "accurate" mode unnecessarily, even when no face is present

Just starting out with react native and I've been exploring the use of expo FaceDetector for detecting faces. In "fast" mode, the "onFacesDetected" event is triggered correctly. However, when switching to "accurate" mode, the "onFacesDetected" event k ...

What is the best way to apply a specific style based on the book ID or card ID when a click event occurs on a specific card in vue.js

My latest project involves creating a page that displays a variety of books, with the data being fetched from a backend API and presented as cards. Each book card features two button sections: the first section includes "ADD TO BAG" and "WISHLIST" buttons ...

generate a cookie within a pop-up window

Can someone help me figure out why my Modal Window with a cookie to display only once isn't working? I followed this tutorial at . Here is the link to my website: Here is my code: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" a ...

JavaScript substring() function in clone is experiencing an error

I am currently working on a JavaScript function that determines whether a specific substring is present in a larger main string. For instance, if the main string is "111010" and the substring is "011," the expected result should be false since the substr ...

"Put Phonegap on hold for a bit and disable landscape mode

I am currently using Phonegap to develop an Android game. My project includes a lobby feature where players can search for opponents and engage in chat with other players. Once a player has found their opponent, they can commence playing the game together ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Creating a selectAll checkbox that triggers the ng-click function on each individual checkbox

I've encountered an issue with my code where clicking a checkbox triggers the ng-click function. Here is the JavaScript snippet: $scope.selectTitle = function(evt, selected){ evt.stopPropagation(); var filtered = _.findWhere($scope.se ...

Steps for extracting HTML content from a beautiful soup object

My current situation involves a bs4 object listing: >>> listing <div class="listingHeader"> <h2> .... >>> type(listing) <class 'bs4.element.Tag'> I am aiming to retrieve the raw html as a string. Initially, ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...