Unable to remove section from task roster

I'm currently working on a task management application, and within this app, there is a container that encompasses an input field (for entering tasks) and an icon from the font-awesome library. When the user interacts with the icon, I intend for the entire container (including the task and delete icon) to be removed. However, my initial attempts at implementing this feature have not been successful. Can someone provide guidance or assistance?

Below is the snippet of JavaScript code being used:

$(document).ready(() => {
    $(".input input").on("keypress", check_todo);
    $(".fa-trash").on("click", ".todo_container", delete_todo);
})

// Function to delete a task
let delete_todo = (e) => {
    e.target.remove();
}

// Function to add a new task
let add_todo = () => {
    let todo = $(".input input").val();

    $(".output").append(`
        <input type="text" placeholder="Edit To-do" value="${todo}"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
        `);
    $(".input input").val("");
}

// Function to validate and process a new task
let check_todo = (e) => {
    if (e.keyCode == 13) {
        if ($(".input input").val() == "") {
            no_todo();
        } else {
            add_todo();
        }
    }
}

// Function called when no task is provided
let no_todo = () => {
    alert("Please add a new todo");
}

If you would like to see the HTML structure and a demo, you can visit the following link: View here

Answer №2

http://codepen.io/anon/pen/eBoXZe

Ensure that in your event listener, the sequence should be changed to swap ".todo_container" and ".fa-trash".

 $(".todo_container").on("click",".fa-trash" , delete_todo);

This logic instructs that when a click event happens and propagates to .todo_container, it will verify if the element clicked is .fa-trash, and if so, execute the designated function.

Next step is to modify your delete function as follows:

let delete_todo = (e) => {
    $(e.currentTarget).closest('.todo_container').remove()
}

This script means starting from the clicked icon, traverse up the document object model (DOM) until it locates .todo_container, then delete it.

Answer №3

Great work incorporating delegation in JQuery! However, be mindful of the static base element $(".todo_container") being deleted in the delete_todo() function.

$(".todo_container").on("click",".fa-trash" , delete_todo);

Consider using $(".output") instead and test if it functions as expected.

Answer №4

Take a look at this functional code snippet:

$(document).ready(function() {
  $(".input input").on("keypress", check_todo);
  //$(".fa-trash").on("click", ".todo_container", delete_todo);
  $(".todo_container .fa-trash").on("click", delete_todo);
})

// function to delete a todo item
let delete_todo = function(e) {
  //e.target.remove();
  $(e.target).parent().remove();
}

// function to add a new todo item
let add_todo = function() {
  let todo = $(".input input").val();

  // Creating the to-do container element with the delete icon appended later
  var toDoContainer = $(`
        <div class="todo_container">
            <input type="text" placeholder="Edit To-do" value="${todo}"></div>
        `);

  // Adding delete icon and setting event listener
  var elem = $('<i class="fa fa-trash fa-lg" aria-hidden="true"></i>').on("click", delete_todo).appendTo(toDoContainer);

  // Appending the new to-do item to the output section
  $(".output").append(toDoContainer);
  $(".input input").val("");
}

// function to check the entered todo item
let check_todo = (e) => {
  if (e.keyCode == 13) {
    if ($(".input input").val() == "") {
      no_todo();
    } else {
      add_todo();
    }
  }
}

// Display an alert if there is no todo item entered
let no_todo = () => {
  alert("Please add a new todo");
}
@font-face {
  font-family: Open Sans;
  src: url("assets/fonts/OpenSans-Regular");
  font-weight: 400
}
@font-face {
  font-family: Open Sans;
  src: url("assets/fonts/OpenSans-Semibold");
  font-weight: 600
}
* {
  margin: 0;
  padding: 0;
  transition: all 200ms ease-in-out;
}
*::selection {
  background-color: #ffffaa;
}
.container {
  width: 60%;
  margin: 20px auto;
}
.header {
  padding: 10px;
}
.header input {
  padding: 10px;
  width: 60%;
  border: none;
  outline: none;
  font: 400 1.8em Open Sans;
}
.to-do {
  padding: 10px;
  text-align: center;
}
.input input {
  padding: 10px;
  width: 40%;
  border: none;
  outline: none;
  font: 600 1em Open Sans;
  border-bottom: 3px solid #333;
}
.output {
  margin: 10px;
}
.output input {
  padding: 20px;
  border: none;
  outline: none;
  font: 600 1em Open Sans;
  width: 50%;
  cursor: pointer;
}
.output input:hover {
  background-color: #eee;
}
.fa-trash {
  padding: 20px;
  cursor: pointer;
}
.fa-trash:hover {
  background-color: #333;
  color: #fff;
}
<head>
  <title>To-do List</title>

  <!-- FONTS -->
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,500" rel="stylesheet">
</head>

<body>
  <div class="container">

    <header class="header">
      <input type="text" name="edit_name" placeholder="Edit Name">
    </header>

    <section class="to-do">
      <div class="input">
        <input type="text" name="add_todo" placeholder="Click To Add A New To-do">
      </div>

      <div class="output">
        <div class="todo_container">
          <input type="text" placeholder="Edit To-do" value="Todo #1"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
        </div>

        <div class="todo_container">
          <input type="text" placeholder="Edit To-do" value="Todo #2"><i class="fa fa-trash fa-lg" aria-hidden="true"></i>
        </div>
      </div>
    </section>

  </div>


  <!-- JQUERY -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

  <script src="https://use.fontawesome.com/5840114410.js"></script>
</body>

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

Tips for showcasing several thumbnails simultaneously as you upload images on a webpage with HTML and JavaScript

function displayImage(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#selectedImage') .attr('src', e.target.result) }; reader.read ...

Understanding the percentages of CSS in relation to other elements

Can you define a CSS dimension in a percentage relative to an element other than its parent? Specifically, I want the border-radius of a div to be 10% of its width. However, using border-radius: 10% creates an elliptical border when the height and width ...

How to resolve the error "TypeError: 'listener' argument must be a function" in Gulpfile.js?

I am in the process of setting up my development environment and encountering some issues when running gulp in the terminal. I am not sure where this error is originating from. Here is the snippet of code from my Gulpfile.js : var gulp = require(&a ...

Generate a navigation route based on the hierarchical relationship between parent and child elements

Here is an array of objects: [ { "id": 1942, "label": "1", "url": "", "homepage": false, "visible": true, "order": 1 }, { "id": 1943 ...

Utilizing the HTML5 Download attribute for linking to external files

I am currently developing a web application for my own personal needs. One feature I would like to implement is the ability to set the download attribute on certain links. However, I have run into an issue where the files to be downloaded are hosted on ex ...

Encouraging an iPhone user to save a favorite Asp.Net MVC developed webpage to their home screen

I created a web application using Asp.Net MVC and included meta tags to give it the look of an iPhone App. Now, I want to know how I can prompt the user to add the page to their home screen when they open the app for the first time on an iPhone, instead of ...

Tips for saving an image that has been dragged onto the browser locally

I recently started working with Angular and decided to use the angular-file-upload project from GitHub here. I'm currently in the process of setting up the backend for my application, but I'd like to be able to display dropped files locally in th ...

Error encountered in AngularJS: Unexpected POST request

I am facing some challenges when trying to send an http post request to the server. I am using PhoneGap to develop an application that utilizes AngularJS. Can someone guide me on how to make a post request using AngularJS? Here is a snippet of my code: . ...

The CSS grid-template-areas feature is not performing as anticipated

.content { width: 600px; height: 600px; border: 4px solid lime; display: grid; grid-template-areas: 'a d' 'b d' 'c d'; } textarea, iframe { margin: 0; box-sizing: border-box; } .content > .a {gri ...

What is the best method to retrieve the initial element in a jQuery slider rotation?

I am trying to vertically center all my images with a height less than 531 pixels within my cycles: before : function(currSlideElement, nextSlideElement, options, forwardFlag){ foto = $(nextSlideElement).find('img'); alert(foto.height()) ...

The issue lies in the fact that the customization of the Ant Design theme is not being properly implemented

I'm in the process of customizing the antd theme in conjunction with next.js. After researching online, I came across a helpful example and implemented the setup like so: // package.json "dependencies": { "@ant-design/icons&quo ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

Incorrect legend colors in Highcharts pie chart

[![enter image description here][1]][1] There seems to be an issue with the Pie-Chart where the Slice color and the Legend color do not match when the color is set using className. This problem does not occur with some other charts. If you look at the co ...

Is it possible that the mouseover event is only triggered once in jQuery?

Whenever the link is hovered over, I need the submit button to move back so that it doesn't overlap with the comment box that appears when the cursor hovers over it. I tried a solution that worked once, but now I need help making it work every time t ...

Creating CSS styles to ensure text takes up the largest size possible without wrapping or extending beyond the screen borders

Looking for a way to display text at its maximum size without any wrapping or overflowing the screen? I attempted using @media and adjusting font-size, but things got too complex. My goal is to have the text on example.com displayed at the largest possible ...

The form keeps getting submitted non-stop on Internet Explorer browser

module.provideSecurityKey = function () { bootbox.prompt(message, function (result) { if (result === null) { //Prompt dismissed } else { var isValid = module.CheckSecurityKey(result); if (!isValid) { ...

"Utilizing JavaScript to filter JSON data at a deep nested

When working with a JSON data set, I often face the challenge of filtering based on specific child values. Take the following example: [ { "Date": "2017-03-02T00:00:00", "Matches": [ { "Id": 67, ...

How is the same-domain policy applied to popup windows that have JavaScript enabled in the URL?

Is it possible to achieve something similar to this? var w = window.open("javascript: makeAnAjaxRequest();"); I'm curious whether the Ajax request, which is triggered after the new window is opened, would be considered a cross-site request. Does the ...

Here’s a guide on accessing variable values from different JavaScript files in Nuxt.js

In my Nuxt.js project, I organized the file directories as follows: <pre> /* Create a axios instance with custom headers */ import axios from 'axios'; let myVariable = someVariable //someVariable is the result from // asynchronous //r ...

Centering the Navbar in Bootstrap 3.0

I am currently in the process of migrating my project from Bootstrap 2.3.2 to Bootstrap 3. Unfortunately, I am facing issues with centering the navbar links, something that I was able to do easily before. Previously, I used this method: Center bootstrap&# ...