How do I remove an object from an array on click? Javascript - javascript

I'm adding hours and dates which are displayed in a list and then pushing the values to an array.
A button is created next to each list item and I want to be able to remove the specific list item on click.
I've tried splice, slice and remove but I'm not able to make it work as I want.
let vacationList = [];
$('#add').click(function(e){
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
??
});
vacationList.push({vacationHours: Number(vacationHours), vacationDates: vacationDates});

Element.remove() should work for the dom element. If you want also remove from array please provide the adding to array code.
$('#add').click(function(e) {
e.preventDefault();
let vacationHours = $('#vacationHours').val();
let vacationDates = document.querySelector("#vacationDates").value;
const li = document.createElement("li");
li.innerText = vacationHours + "h - " + vacationDates;
const button = document.createElement("button");
button.className = "fa fa-minus-circle";
const ul = document.querySelector(".list");
ul.appendChild(li);
li.appendChild(button);
button.addEventListener('click', (e) => {
e.preventDefault()
this.closest("li").remove();
});
});

Related

How to create a dynamic list, which removes deleted items from an array in JS?

I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.
For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin.
How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help.
Here is my code:
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
output.removeChild(paragraph)
})
})
You can find an element in the array by name and remove it from there:
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
output.removeChild(paragraph)
})
})
<input id="name">
<button id="button">button</button>
<div id="output">output</div>
Every time the event handler to delete an item is called, just collect all of the text of each item and convert it into an array.
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
/*
This removes an <li>, if you don't change your "paragraph" then
change 'li' to 'ul'
*/
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const item = document.createElement('li');
item.textContent = name+' ';
list.append(item);
const del = document.createElement('button');
del.textContent = "X";
item.append(del);
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});
<input id='user'><button class='add'>ADD</button>
<ul class='list'></ul>
Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const paragraph = document.createElement('div')
paragraph.style.display = 'flex'
const item = document.createElement('li');
item.textContent = name + ' ';
list.append(paragraph);
paragraph.append(item)
const del = document.createElement('button');
del.textContent = "X";
paragraph.append(del);
del.addEventListener('click', function() {
this.closest('div').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});

Add button after clicking an list in javascript

Im trying to add button "edit" and "delete" into list element after clicking on it.
Ive added 2 buttons to list element and set their display to none in class btnedit and btndelete:
function Add(){
let li = document.createElement('li');
let a = document.createElement('a');
let button1 = document.createElement('button');
let button2 = document.createElement('button');
button1.innerHTML = "Edit";
button2.innerHTML = "Delete";
button1.setAttribute('class','BtnEdit');
button2.setAttribute('class','BtnDelete');
let input = document.getElementById('AddText').value;
if (input.length < 3){
alert('Must be longer than 3');
}
else if(input.length > 255){
alert('Cant be longer than 255');
}
else {
if (checkDate()!=null) {
let date = checkDate();
let t = document.createTextNode(`${input} ${date}`);
let test = new storage1(input,date);
store(test);
li.appendChild(a);
a.appendChild(t);
document.getElementById("myList").appendChild(li).appendChild(a);
li.appendChild(button1);
li.appendChild(button2);
}
}
In this function I change their background color when i click on list element:
let list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
but i have no idea how to display buttons now
Change the display:
button1.style.display = "inline";
or remove the class:
button1.classList.remove("BtnEdit");

create and add "li" element after click

In an exercise, I have created a new element li after each click of my button.
It doesn't work. In the console it reports "li is not defined".
What did I do wrong?
My code:
const btn = document.querySelector("button");
let number = 1;
const ul = document.querySelector("ul");
const fcn = function() {
const li = document.createElement('li');
li.textContent = number;
}
if (number % 3 == 0) {
li.classList.add('big');
}
ul.appendChild(li);
number += 2;
btn.addEventListener("click", fcn);
try this:
const btn = document.querySelector("button");
let number = 1;
const ul = document.querySelector("ul");
const fcn = function () {
const li = document.createElement('li');
li.textContent = number;
if (number % 3 == 0) {
li.classList.add('big');
}
ul.appendChild(li);
number += 2;
}
btn.addEventListener("click", fcn);
This problem is related to closures in javascript. li is not accessible outside function fcn.
following code should solve your problem.
const btn = document.querySelector("button");
let number = 0;
const ul = document.querySelector("ul");
const fcn = function () {
number += 1;
const li = document.createElement('li');
li.textContent = number;
ul.appendChild(li);
if (number % 3 == 0) {
li.classList.add('big');
}
}
btn.addEventListener("click", fcn);
li is defined within anonymous function.
When you define a variable/constant within function it's local to that function and can't be accessed outside it. It has function level scope.
To fix your code either define li outside of function at global scope or move the piece of code that use it within function itself as follows :
const btn =
document.querySelector("button");
let number = 1;
const ul =
document.querySelector("ul");
const fcn = function () {
const li =
document.createElement('li');
li.textContent = number;
if(number % 3 == 0){
li.classList.add('big');
}
ul.appendChild(li);
number += 2;
}
btn.addEventListener("click", fcn);

How do I delete an <li> on click with vanilla javascript?

I'm having trouble finding the right syntax to use to delete an element. I have a list item that I generate with a form that I want to also be deleted when I click on it. Here is my current javascript code:
// add to do items
let todoList = [];
function addTodo(item){
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
const listItems = document.querySelectorAll('li');
addButton.addEventListener('click', function(){
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
});
So far I can add an item to my todo list but how do I go about deleting it with a click?
You can add an onclick listener to the newly created li element to remove it when clicked:
todoLi.onclick = (e) => e.target.remove();
// add to do items
let todoList = [];
function addTodo(item) {
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
const listItems = document.querySelectorAll('li');
addButton.addEventListener('click', function() {
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoLi.onclick = (e) => e.target.remove();
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
});
<button class="btn__display">btn__display</button>
<input type="text" class="addItem">
<ul></ul>
Similar to Luis's answer, you can do the following:
// add to do items
let todoList = [];
function addTodo(item){
todoList.push(item);
//display item
}
const addButton = document.querySelector('.btn__display');
const formInput = document.querySelector('.addItem');
addButton.addEventListener('click', function(){
const todoUl = document.querySelector('ul');
const todoLi = document.createElement('li');
todoLi.textContent = formInput.value;
todoList.push(formInput.value);
todoUl.appendChild(todoLi);
formInput.value = '';
todoLi.addEventListener('click', function () {
this.remove();
});
});
The difference being that we are instead adding the event listener with a function where this will be set to the list item.
https://jsfiddle.net/gy9cLum3/
Try with this code:
<ul>
<li onclick="remove(this)">lorem</li>
</ul>
<script>function remove(elem) { elem.parentElemet.removeChild(elem); } </script>

Create span element in li with Javascript

I'm working on a to-do list project and when creating a new li I would like it to start with a span containing a "X". I wrote the code below, but instead of a span I get "[object HTMLSpanElement]". Anybody knows how to fix this? Thank you!
var enterItem = document.querySelectorAll("input");
var todoList = document.getElementById("todo-list");
for (var i = 0; i < enterItem.length; i++) {
enterItem[i].addEventListener("keypress", function(key) {
if(key.which === 13){
var newLi = document.createElement("li");
var span = document.createElement("span");
var newItem = this.value;
span.textContent = "X";
newLi.appendChild(document.createTextNode(span + " " + newItem));
todoList.appendChild(newLi);
this.value = "";
}
});
}
You are trying to add an html element in a textNode so it triggers the toString of the element
You need
const todoList = document.getElementById("todo-list");
document.getElementById("inputContainer").addEventListener("keypress", function(e) {
const tgt = e.target;
if (tgt.type === "text" && e.which === 13) {
let newLi = document.createElement("li");
let span = document.createElement("span");
span.classList.add("remove");
let newItem = tgt.value;
span.textContent = "X";
newLi.appendChild(span)
newLi.appendChild(document.createTextNode(" " + newItem));
todoList.appendChild(newLi);
tgt.value = "";
}
});
document.getElementById("todo-list").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("remove")) {
tgt.closest("li").remove();
}
})
<div id="inputContainer">
<input type="text" />
</div>
<ul id="todo-list"></ul>

Categories

Resources