Is there a way to incorporate a delete button for each li element that is included in my list?

I have successfully implemented a to-do list where clicking on an item strikes a line through it and there is a delete button that works. However, I am looking for assistance on how to create a delete button for each newly added li item.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var btn1 = document.getElementById("btn1");

ul.addEventListener("click", function(ev) {
  if (ev.target.tagName === "LI") {
    ev.target.classList.toggle('checked');
  }
}, false);

function inputLength() {
  return input.value.length;
}

function deleteBtn() {
  var myList = document.getElementsByTagName("li");
  for (var i = 0; i < myList.length; i++) {
    deleteButton.onclick = this.parentElement.style.display = "none";
  }
}

function createListElement() {
  var myList = document.getElementsByTagName("li");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}


function addListAfterKeypress() {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

btn1.addEventListener("click", deleteBtn);
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
ul li.checked {
  text-decoration: line-through;
}
<input id="userinput" type="text" placeholder="enter list item here">
<button id="enter">Add</button>

<ul id="myUL">
  <li>eggs</il><button id="btn1">delete</button>
    <li>milk</li>
    <li>tacos</li>
</ul>

In the deleteBtn function I tried adding

deleteButton = document.createElement("button");
deleteButton.appendChild.createTextNode("delete);

right after the for loop but I couldn't get it to work. I also tried adding it in the createListElement function and I couldn't get that to work either. Any help or suggestions would be greatly appreciated.

Answer №1

I have implemented a new feature where a class called .deletebtn is added to each newly created button. Each of these buttons now has a click event listener attached to them, allowing them to execute independently.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var btn1 = document.getElementById("btn1");

ul.addEventListener("click", function(ev) {
  if (ev.target.tagName === "LI") {
    ev.target.classList.toggle('checked');
  }
}, false);

function inputLength() {
  return input.value.length;
}

function createListElement() {
  var myList = document.getElementsByTagName("li");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(input.value));
  ul.appendChild(li);
  input.value = "";
  var deleteButton = document.createElement("button");

  deleteButton.appendChild(document.createTextNode("delete"));
  li.appendChild(deleteButton);
  deleteButton.onclick = function() {
    this.parentElement.style.display = "none";
  }
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}

function addListAfterKeypress() {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
ul li.checked {
  text-decoration: line-through;
}
<input id="userinput" type="text" placeholder="enter list item here">
<button id="enter">Add</button>

<ul id="myUL">
</ul>

Answer №2

What do you think of this one? It seems promising.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var btn1 = document.getElementById("btn1");

ul.addEventListener("click", function(ev) {
  if (ev.target.tagName === "LI") {
    ev.target.classList.toggle('checked');
  }
}, false);

function inputLength() {
  return input.value.length;
}

function deleteBtn() {
  var myList = document.getElementsByTagName("li");
  for (var i = 0; i < myList.length; i++) {
    deleteButton.onclick = this.parentElement.style.display = "none";
  }
}

function createListElement() {
  var myList = document.getElementsByTagName("li");
  var li = document.createElement("li");
  var btn = document.createElement("button");
  btn.innerText = "delete";
  btn.onclick = () => ul.removeChild(li);
  li.appendChild(document.createTextNode(input.value));
  li.appendChild(btn);
  ul.appendChild(li);
  input.value = "";
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}


function addListAfterKeypress() {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

btn1.addEventListener("click", deleteBtn);
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
ul li.checked {
  text-decoration: line-through;
}
<input id="userinput" type="text" placeholder="add new item here">
<button id="enter">Add Item</button>

<ul id="myUL">
  <li>apples</il><button id="btn1">delete</button>
    <li>oranges</li>
    <li>bananas</li>
</ul>

Answer №3

You can streamline the process by integrating buttons and text within <li> tags, and then hide the parent element when the delete function is triggered.

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");
var li = document.getElementsByTagName("li");
var btn1 = document.getElementById("btn1");

ul.addEventListener("click", function(ev) {
  if (ev.target.tagName === "LI") {
    ev.target.classList.toggle('checked');
  }
}, false);

function inputLength() {
  return input.value.length;
}

function deleteBtn(obj) {
  console.log(obj);
  obj.parentElement.style.display = "none";
}

function createListElement() {
  var myList = document.getElementsByTagName("li");
  let node = document.createElement('li');
  node.innerHTML = `${input.value}&nbsp;<button id="btn${myList.length}" onclick="deleteBtn(this)">delete</button>`;
  ul.appendChild(node);
  input.value = "";
}

function addListAfterClick() {
  if (inputLength() > 0) {
    createListElement();
  }
}


function addListAfterKeypress() {
  if (inputLength() > 0 && event.keyCode === 13) {
    createListElement();
  }
}

//btn1.addEventListener("click", deleteBtn);
button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);
ul li.checked {
  text-decoration: line-through;
}
<input id="userinput" type="text" placeholder="enter list item here">
<button id="enter">Add</button>
<ul id="myUL">
</ul>

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

Is there a way to eliminate the return?

Struggling to eliminate the unwanted return in my Wordpress loop. The layout is ruined by trying to display a thumbnail next to the entry: https://i.sstatic.net/j3Ozz.png Even using padding for the entry made it worse! Here's the code snippet that ...

How can we prevent the restoration of size effects in jQuery UI versions 1.9 and above?

After implementing jQuery UI 1.9 or newer, I noticed that the size effect returns to its original state. Below is a snippet of my code: http://jsfiddle.net/mQCxY/ $(function () { $('.circle').click(function () { $(this).effect("size ...

Why is the official website for the Apache HTTP Server httpd.apache.org when HTTPd is actually a program that can be run?

After conducting thorough research, I discovered that HTTPd (HyperText Transfer Protocol daemon) is a software program that operates in the background of a web server. My amazement and confusion peaked when I came across the webpage 'httpd.apache.org ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

Altering the ASP DropDownList's background color solely with CSS modifications

Is there a way to change the background colors of dropdownlists in my C# web app using CSS instead of specifying each one individually? In simpler terms, I'm trying to avoid having to write out code like this for multiple dropdowns: private void For ...

What is the best way to apply padding to the top of a div when it is positioned below another div?

Observing the minimal spacing between the divs AboutDogs and AboutCats, I decided to apply padding-top: 20px to the AboutCats to create a visual distinction. However, I encountered a scenario where only AboutCats exists without any other div above it. In ...

browsing through a timeline created using HTML and CSS

I am currently working on a web project that involves creating a timeline with rows of information, similar to a Gantt chart. Here are the key features I need: The ability for users to scroll horizontally through time. Vertical scrolling capability to na ...

The combination of Node.js and a Telegram bot

I am trying to utilize a telegram bot to access a specific route on a website. Within the website's routes.js file, I have: app.get('/api/getalert', getAlert); and var getAlert = function(req, res) { var id = req.query.id; ...

Storing JSON data in a SQL database

Storing JSON in an MsSql database and passing it to Javascript via a PHP script has been working perfectly. However, when trying to include extra text that is not part of the formatting string, like d, h, a, or p characters, encountered some challenges. Lu ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

Tips for adding a "Select All" feature to a dropdown list?

Currently, I have a dropdown list with a filter for IN and OUT values. The functionality is working as expected: <select class="form-select" style="max-width: 100px" [ngModel]="selectedBrand" (ngModelChange)="onChangeT ...

Confirming Bootstrap - Implement an onConfirm method for element attributes

I am looking to add a JavaScript function to my confirmation button. I have created the elements off-page and fetched them using ajax, so it is crucial that I can set the function in-properties rather than via $('#id').confirmation() So far, I h ...

To trigger a Bootstrap 5 modal in a child component from a button click in the parent component in Angular without the need to install ng-bootstrap is possible with the following approach

To achieve the functionality of opening a modal in a child component upon clicking a button in the parent component without using ngx-bootstrap due to restrictions, one approach is to add data-bs-target and data-bs-toggle attributes to the button. Addition ...

Displaying AJAX data in Django using an HTML table

My Django template currently has the following AJAX script running: function create_table() { $.ajax({ method: "GET", url: "/api/data/", success: function(data){ console.log('button clicked') ...

What is the best way to generate an extensive table with HTML and AngularJS?

I am looking to implement an expandable table feature where a single header with a plus icon can be clicked to reveal the child rows beneath it. Currently, I have been able to achieve this functionality. However, I am facing an issue where the child rows ...

What is the best way to show an element when hovering over another element?

I'm looking for a CSS-only solution (NO JQuery) to display a FontAwsome icon (<i class='fas fa-arrow-alt-circle-left fa-lg arrowbounce text-success hidearrowbounce'></i>) only when hovering over another element. However, despite ...

What is the best way to retrieve a value from a database and display it in a radio

Can you help me figure out how to implement this functionality? I have a database with a "boolean" field that stores 0 or 1 values. On an HTML page, there is a radioButton with options for OK or NO. I need to dynamically load the boolean value from the dat ...

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...

What could be causing my div element to not inherit its parent div's width?

My query revolves around a header div that I'm struggling to align with the same width as its parent div, while keeping the content centered. Currently, the div is only as wide as its content, causing it to be off-center. https://i.stack.imgur.com/E1 ...

Issues with hidden overflow and height attributes not functioning correctly in Internet Explorer 9 when using the DOCTYPE HTML standards mode

I have a <div> with overflow:hidden and height:100% that adjusts the div contents to fit the window's height on Chrome and Safari. However, in IE9, the div does not respect the styles of overflow:hidden and height:100%, causing it to expand to ...