how to subtract a number on the second button click? - javascript

function createElement(){
const input = document.getElementById("input");
const ul = document.getElementById("ul");
const li = document.createElement("li");
const div = document.createElement("div");
div.innerText = input.value;
const btn = document.createElement("button");
btn.innerText = "add 2";
li.appendChild(div);
li.appendChild(btn);
ul.appendChild(li);
btn.onclick = () => {
let num = parseInt(div.innerText);
num = num + 2;
const roundednum = num.toFixed(2);
div.innerText = roundednum;
btnCLicked = true;
}
}
document.getElementById("btn").addEventListener("click", createElement);
<input type="number" id="input">
<ul id="ul"></ul>
<button id="btn">click me</button>
i have this simple code above that creates some elements, and it will add 2 to the number in the div when button inside the <li> is clicked, which works perfectly
now i want to subtract 2 from the number when button is clicked the second time, so first click will add 2, second click will subtract 2
so i come up with this code which uses a boolean to add and subtract the number which works
let btnCLicked = false;
function createElement(){
const input = document.getElementById("input");
const ul = document.getElementById("ul");
const li = document.createElement("li");
const div = document.createElement("div");
div.innerText = input.value;
const btn = document.createElement("button");
btn.innerText = "add 2";
li.appendChild(div);
li.appendChild(btn);
ul.appendChild(li);
btn.onclick = () => {
if (btnCLicked === false) {
let num = parseInt(div.innerText);
num = num + 2;
const roundednum = num.toFixed(2);
div.innerText = roundednum;
btnCLicked = true;
}else if (btnCLicked === true) {
let num = parseInt(div.innerText);
num = num - 2;
const roundednum = num.toFixed(2);
div.innerText = roundednum;
btnCLicked = false;
}
}
}
document.getElementById("btn").addEventListener("click", createElement);
<input type="number" id="input">
<ul id="ul"></ul>
<button id="btn">click me</button>
but now the problem is that when i create an <li>, and click the button inside to add 2 to the number, btnClicked is now set to true.
so when i create another element and click the button for the first time it will subtract the number because btnClicked is true, which is what i dont want, i want the first click to add and subtract on the second click
how do i solve that problem? im thinking about something like making the boolean only inside each li so each li has an own boolean and it will not effect other elements but idk lol i have no other idea

Move the let btnCLicked = false; into the function. Each invocation of createElement() will create a [closure`]1 since it's child function (click handler) is using variables from parents scope:
const input = document.getElementById("input");
const ul = document.getElementById("ul");
function createElement() {
let btnCLicked = false;
const li = document.createElement("li");
const div = document.createElement("div");
const btn = document.createElement("button");
div.innerText = input.value || 0;
btn.innerText = "add 2";
li.appendChild(div);
li.appendChild(btn);
ul.appendChild(li);
btn.onclick = () => {
let num = Number(div.innerText);
if (btnCLicked === false) {
num += 2;
} else {
num -= 2;
}
div.innerText = num;
btnCLicked = !btnCLicked;
}
}
document.getElementById("btn").addEventListener("click", createElement);
<input type="number" id="input">
<ul id="ul"></ul>
<button id="btn">click me</button>

Another solution: use event delegation and use a data-attribute to track the last action (add or subtract):
document.addEventListener("click", handle);
function createElement() {
document.querySelector("#ul").insertAdjacentHTML("beforeend", `
<li>
<div>${(+document.querySelector("#input").value).toFixed(2)}</div>
<button data-action="add">2</button>
</li>`);
}
function handle(evt) {
const origin = evt.target;
if (origin.id === "btn") {
return createElement();
}
if (origin.dataset.action) {
return addOrSubtract2(origin);
}
}
function addOrSubtract2(fromBttn) {
const parentLi = fromBttn.closest("li");
const add = fromBttn.dataset.action === "add";
const num = +(parentLi.querySelector("div").textContent) + (add ? 2 : -2);
fromBttn.dataset.action = add ? "subtract" : "add";
parentLi.querySelector("div").textContent = num.toFixed(2);
}
[data-action]:before {
content: attr(data-action)' ';
}
<input type="number" id="input" value=0 step="0.1">
<button id="btn">create new</button>
<ul id="ul"></ul>

Related

A function to remove a div element that contains specific text in Javascript?

I've written a simple code that takes text from the input field, stores it as a string in an array and creates a div with that same text every time the "add" button is pressed.
Then there's a "remove" button, that removes the item from array if the input matches the item in the array.
I need a function to remove the previously created div with the same text inside as the current input.
E.g. if I type "book1" press "add" - array gets 'book1' as a first item and a div "book1" is created, "book2", "book3" and so on. If I type 'book2' and press remove, it gets removed from the array and a respective div should be removed.
That last function I just can't figure out.
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
let innerDiv = document.body.newDiv.innerHTML
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement()
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
function removeElement() {
alert("this bit needs working out");//???
}
<input type="text" id="input" />
<button id="add-btn">Add</button>
<button id="rmv-btn">Remove</button>
<div id="mydiv"></div>
</div>
You need to change how you are adding the div because it adding it outside and not as a child of my_div
let addBtn = document.getElementById("add-btn");
let removeBtn = document.getElementById("rmv-btn");
let bookArray = [];
addBtn.addEventListener("click", addBook);
removeBtn.addEventListener("click", removeBook);
function addBook() {
newBook = document.getElementById("input").value;
if (newBook != '') {
bookArray.push(newBook);
addElement();
clear();
console.log(bookArray);
} else {
clear();
console.log(bookArray);
}
}
function removeBook() {
inputBook = document.getElementById("input").value;
for (i = 0; i < bookArray.length; i++) {
if (inputBook.toString() === bookArray[i].toString()) {
bookArray.splice([i], 1);
console.log(bookArray);
removeElement(i);
return;
} else {
clear();
}
}
console.log(bookArray);
}
function clear() {
document.getElementById("input").value = "";
}
function addElement() {
let newDiv = document.createElement("div");
// count number of children in mydiv
let count = document.getElementById("mydiv").childElementCount;
// add an id
newDiv.id = 'mydiv-' + count;
newDiv.innerHTML = newBook;
my_div = document.getElementById("mydiv");
my_div.appendChild(newDiv, my_div);
}
function removeElement(el) {
// remove html element from dom
let my_div = document.getElementById("mydiv");
my_div.removeChild(my_div.childNodes[el]);
}
A workaround to remove book by the input value by user:
Modify the addElement function to:
function addElement() {
let newDiv = document.createElement("div");
newDiv.innerHTML = newBook;
newDiv.setAttribute('data-book-name', newBook); //new added line | setting data attribute
my_div = document.getElementById("mydiv");
document.body.appendChild(newDiv, my_div);
}
removeElement will be:
function removeElement() {
document.querySelector('[data-book-name="'+ newBook +'"]')?.remove();
}
But this will remove first book in the DOM. If you want to remove all books with same name use:
function removeElement() {
var books = document.querySelectorAll('[data-book-name="'+ newBook +'"]');
if(books.length == 0) return;
books.forEach(x => x.remove())
}

JavaScript adding event on element generated element with innerHtml

I want to add an event on an element does doesn't exist in the original HTML (created with innerHtml). When i click nothing happens.
const btnRemove = document.getElementById("remove");
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
});
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
I want to add a click event on the element with id remove.
Another way to do that is creating the elements instead of use the HTML code and a later search. This maybe useful if you, for example, don't want to add an id to the remove tag
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = document.createElement("div");
div.className = "v1";
service.appendChild(div);
var p1 = document.createElement("p");
p1.className = "v3-text";
div.appendChild(p1);
var p1Text = document.createTextNode("Mown Lawn ");
p1.appendChild(p1Text);
var p1Span = document.createElement("span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
p1.appendChild(p1Span);
var p2 = document.createElement("p");
p2.className = "v3-dollar";
p2.innerHTML = "<span>$</span>20";
div.appendChild(p2);
sMow = false;
total += 20;
totalC();
}
});
As you can see, creating the elements allow you do whatever you want with it. It's longer but you can use a helper function like this:
function appendTag(parent, tagName, className) {
var tag = document.createElement(tagName);
if (className)
tag.className = className;
parent.appendChild(tag);
return tag;
}
And rewrite as:
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
var div = appendTag(service, "div", "v1");
var p1 = appendTag(div, "p", "v3-text");
p1.appendChild(document.createTextNode("Mown Lawn "));
var p1Span = appendTag(p1, "span");
p1Span.setAttribute("id", "remove");
p1Span.innerText = "remove";
p1Span.addEventListener("click", function remove() {
alert("HELLO");
});
var p2 = appendTag(p1, "p", "v3-dollar");
p2.innerHTML = "<span>$</span>20";
sMow = false;
total += 20;
totalC();
}
});
btnMow.addEventListener("click", function mow() {
if (sMow === true) {
reqServices.push("Mow Lawn");
service.innerHTML += `
<div class="v1">
<p class="v3-text">Mown Lawn <span id="remove">remove</span></p>
<p class="v3-dollar"><span>$</span>20</p>
</div>`;
sMow = false;
total += 20;
totalC();
}
const btnRemove = document.getElementById("remove");
btnRemove.addEventListener("click", function remove() {
alert("HELLO");
});
});
var btnremove = document.getElementById("remove");
write this before starting click event

Trying to create a button with an li and it's not working

I'm trying to make a grocery list app using an array similar to a todo list. I've got it working with an add button, and had a remove button that would remove an item from the list. But now I'm trying to make it so that a remove button is created with each li so that each grocery item can be selectively removed. I gave it a shot but I'm not quite sure what I've done wrong here.
let addButton = document.getElementById('add-button');
addButton.addEventListener('click', add);
let addInput = document.getElementById('add-input');
//let removeButton = document.getElementById('remove-button');
//removeButton.addEventListener('click', remove);
let groceryList = [
]
function add() {
groceryInput = addInput.value;
groceryList.push(groceryInput);
addInput.value = '';
displayGroceries();
}
function remove(event) {
let position = event.currentTarget.id;
groceryList.splice(position, 1);
displayGroceries();
}
function displayGroceries() {
let groceryUl = document.getElementById('grocery-ul');
groceryUl.innerHTML = '';
for (let i = 0; i < groceryList.length; i++) {
let groceryLi = document.createElement('li');
groceryLi.innerHTML = groceryList[i];
groceryUl.appendChild(groceryLi);
}
let removeButton = document.createElement('button');
removeButton.innerText = "Remove";
removeButton.addEventListener('click', remove);
removeButton.id = i;
groceryLi.appendChild(removeButton);
}
<div class="container">
<h1>Grocery List</h1>
<input id="add-input" placeholder="Add Groceries" autocomplete="off">
<button id="add-button">Add</button>
<!--<button id="remove-button">Remove</button>-->
<div>
<ul id="grocery-ul"></ul>
</div>
Its not working as groceryLi.appendChild(removeButton) you are calling outside for loop.
You have defined groceryLi using let and let have a block scope.
Moving code to add button inside resolves issue
Find fixed method for displayGroceries as follows
function displayGroceries() {
let groceryUl = document.getElementById('grocery-ul');
groceryUl.innerHTML = "";
for (let i = 0; i < groceryList.length; i++) {
let groceryLi = document.createElement("li");
groceryLi.innerHTML = groceryList[i];
let removeButton = document.createElement("button");
removeButton.innerText = "Remove";
removeButton.addEventListener("click", remove);
removeButton.id = i;
groceryLi.appendChild(removeButton);
groceryUl.appendChild(groceryLi);
}
}
In your example you are calling on the incrementing value of i outside of the scope of its loop.
You can create the button using the same method you are using to create your list item tag, then add the button to the UL element tag using .insertAdjacentElement('beforeend', removeBtn).
Then you can use a removeEl function that looks at the event.target parentNode and firstChild --> li that will contain the grocery item and its remove button to both remove the element from the DOM and the array.
function removeEl(event) {
event.target.parentNode.remove(event.target)
if (groceryList.includes(event.target.parentNode.firstChild.textContent)) {
let k = groceryList.indexOf(event.target.parentNode.firstChild.textContent);
if (k !== -1) {
groceryList.splice(k, 1);
}
}
displayGroceries();
}
//and the for loop that creates the new elements in displayGroceries()
for (let i = 0; i < groceryList.length; i++) {
let groceryLi = document.createElement('LI');
let removeBtn = document.createElement('BUTTON');
groceryUl.classList.add('flex-display')
removeBtn.textContent = `remove ${groceryList[i]}`;
removeBtn.setAttribute('onclick', `removeEl(event)`)
groceryLi.innerHTML = groceryList[i];
groceryUl.appendChild(groceryLi);
groceryLi.insertAdjacentElement('beforeend', removeBtn);
}
let addButton = document.getElementById('add-button');
addButton.addEventListener('click', add);
let addInput = document.getElementById('add-input');
//let removeButton = document.getElementById('remove-button');
//removeButton.addEventListener('click', remove);
let groceryList = [
]
function add() {
groceryInput = addInput.value;
groceryList.push(groceryInput);
addInput.value = '';
displayGroceries();
}
function removeEl(event) {
//this targets the LI element, parent of the button
event.target.parentNode.remove(event.target)
//event.target.parentNode.firstChild.textContent -> the grocery item
if (groceryList.includes(event.target.parentNode.firstChild.textContent)) {
// get the index
let k = groceryList.indexOf(event.target.parentNode.firstChild.textContent);
if (k !== -1) {
groceryList.splice(k, 1);
}
}
displayGroceries();
}
function displayGroceries() {
let groceryUl = document.getElementById('grocery-ul');
groceryUl.innerHTML = '';
for (let i = 0; i < groceryList.length; i++) {
let groceryLi = document.createElement('LI');
let removeBtn = document.createElement('BUTTON');
groceryUl.classList.add('flex-display')
removeBtn.textContent = `remove ${groceryList[i]}`;
removeBtn.setAttribute('onclick', `removeEl(event)`)
groceryLi.innerHTML = groceryList[i];
groceryUl.appendChild(groceryLi);
groceryLi.insertAdjacentElement('beforeend', removeBtn);
}
}
.flex-display {
display: flex;
align-items: start;
flex-direction: column;
}
li {
list-style: none;
}
button {
margin-left: 1rem;
}
<div class="container">
<h1>Grocery List</h1>
<input id="add-input" placeholder="Add Groceries" autocomplete="off">
<button id="add-button">Add</button>
<!--<button id="remove-button">Remove</button>-->
<div>
<ul id="grocery-ul">
</ul>
</div>

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);

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