What can I do to mix operations ? with vanilla javascript [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working on a simple calculator that implements a sum, rest, multiplication, and division.
I would like to take the inner text inside of any button with the class "number" to use it later like a number to pass through a function that does the math.
These are the functions to work with the calculator.
const add = (num1, num2) => {
return num1 + num2;
};
const subtract = (num1, num2) => {
return num1 - num2;
};
const multiply = (num1, num2) => {
return num1 * num2;
};
const divide = (num1, num2) => {
return num1 / num2;
};
// Our Buttons
const outPut = document.getElementById('output');
const num = document.getElementsByClassName('number');
const addBtn = document.querySelector('.addOperator');
const subtractBtn = document.querySelector('.subtractOperator');
const multiplyBtn = document.querySelector('.multiplyOperator');
const divideBtn = document.querySelector('.divideOperator');
const allClear = document.querySelector('.ac');
const equals = document.querySelector('.equals');
let plusFirsValue = '';
let secondValue = 0;
let subFirstValue = 0;
let multFirstValue = 0;
let divFirstValue = 0;
for(let i = 0; i < num.length; i++) {
num[i].addEventListener('click', () => {
outPut.innerText += num[i].innerText;
console.log(outPut.innerText);
});
};
addBtn.addEventListener('click', () => {
plusFirsValue = Number(outPut.innerText);
outPut.innerText = '';
console.log(plusFirsValue);
});
subtractBtn.addEventListener('click', () => {
subFirstValue = Number(outPut.innerText);
outPut.innerText = '';
console.log(plusFirsValue);
});
multiplyBtn.addEventListener('click', () => {
multFirstValue = Number(outPut.innerText);
outPut.innerText = '';
});
divideBtn.addEventListener('click', () => {
divFirstValue = Number(outPut.innerText);
outPut.innerText = '';
});
equals.addEventListener('click', () => {
secondValue = Number(outPut.innerText);
if (plusFirsValue && secondValue) {
outPut.innerText = add(plusFirsValue, secondValue);
console.log(add(plusFirsValue, secondValue));
} else if (subFirstValue && secondValue) {
outPut.innerText = subtract(subFirstValue, secondValue);
console.log(subtract(subFirstValue, secondValue));
} else if (multFirstValue && secondValue) {
outPut.innerText = multiply(multFirstValue, secondValue);
console.log(multiply(multFirstValue, secondValue));
} else if (divFirstValue && secondValue) {
outPut.innerText = divide(divFirstValue, secondValue);
console.log(divide(divFirstValue, secondValue));
}
});
allClear.addEventListener('click', () => {
outPut.innerText = '';
})
<div id="calculator-grid">
<div id="output"></div>
<button class="ac">AC</button>
<button class="sun">Sun</button>
<button class="divideOperator">÷</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button class="multiplyOperator">*</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button class="addOperator">+</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="subtractOperator">-</button>
<button class="number">0</button>
<button class="number">.</button>
<button class="equals">=</button>
</div>
Some of the implementation I would like to do is a mix between operations that means, after a sum between 2 numbers I want to rest other. For example 3 + 3 = 6 but then 6 - 3 = 3 in the same operation. What can I do?

Notice that in your code the first selector (of button with class of 'number') you assign an array with less members than the second selector (where you select ALL the buttons) however in the loop you using the index of numbers.
const btn = document.getElementsByTagName('button');
const inp = document.getElementById('output');
for (let i = 0; i < btn.length; ++i) {
btn[i].addEventListener('click', () => {
inp.innerText += btn[i].innerText;
});
Event listeners added to all of the button and the innerText of the div with id of 'output' is modified by clicking one of the buttons.

Related

I am trying to push a value onto an array with .push(), but it stops pushing values once the array length reaches two

I'm trying to create a javascript calculator for The Odin Project. I finally felt like I was making a bit of progress, after headbutting my keyboard for hours, and then this weird bug arose.
In the function where I add event listeners to the operator buttons, I am trying to push the current operator (the last one which was clicked) on to an array which keeps track of the operator buttons which have been clicked ('newOperators.push(e.target.innerText)').
If I spam the operator button, it pushes on to the array just fine. But when I am trying to chain together a series of operations, the newOperators.push() method seems to quit after the array length reaches two.
To test, I added another dummy array and pushed letters onto it on using another push() method, which I put on the line above newOperators.push(), and that seems to work just fine. I've tried switching newOperators.push() to newOperators.unshift() and that has the same issue.
Losing my mind here, any help would be much appreciated!
Javascript:
let display = document.querySelector('.display');
let title = document.querySelector('.title');
let plus = document.querySelector('.plus');
let minus = document.querySelector('.minus');
let times = document.querySelector('.multiply');
let divide = document.querySelector('.divide');
let equal = document.querySelector('.equal');
let period = document.querySelector('.period');
let one = document.querySelector('.one');
let two = document.querySelector('.two');
let three = document.querySelector('.three');
let four = document.querySelector('.four');
let five = document.querySelector('.five');
let six = document.querySelector('.six');
let seven = document.querySelector('.seven');
let eight = document.querySelector('.eight');
let nine = document.querySelector('.nine');
let nought = document.querySelector('.nought');
let buttons = document.querySelectorAll('button');
let operators = document.querySelectorAll('.operator');
let numbers = document.querySelectorAll('.number');
let currentCalc = [];
let currentOp = '';
let firstNumber = 0;
let secondNumber = 0;
let thirdNumber = 0;
let firstStash = 0;
let secondStash = 0;
let total = 0;
let calculated = false;
let newOperators = [];
const add = function(a,b) {
return a + b;
};
const subtract = function(a,b) {
return a - b;
};
const multiply = function(a,b) {
return a * b
};
const division = function(a,b) {
return a / b
};
function operate(fnum,snum, op) {
if(op === '+') {
let sum = add(fnum,snum);
return sum;
} else if(op === '-') {
let sum = subtract(fnum,snum);
return sum;
} else if(op === 'x') {
let sum = multiply(fnum,snum);
return sum;
} else if(op === '/') {
let sum = division(fnum,snum);
return sum;
}
}
let fNumArr = [];
let sNumArr = [];
let tNumArr = [];
numbers.forEach((e) => {
e.addEventListener('click', (e) => {
console.log('numberFunc', newOperators)
if(newOperators.length < 1) {
fNumArr.push(e.target.innerText)
firstNumber = parseInt(fNumArr.join(''));
console.log('first',firstNumber);
display.textContent = firstNumber;
} else if( newOperators.length = 1) {
sNumArr.push(e.target.innerText);
secondNumber = parseInt(sNumArr.join(''));
console.log('second',secondNumber);
display.textContent = secondNumber;
} else if(newOperators.length > 1) {
tNumArr.push(e.target.innerText);
thirdNumber = parseInt(tNumArr.join(''));
console.log('third',thirdNumber);
display.textContent = thirdNumber;
}
})
})
operators.forEach((e) => {
e.addEventListener('click', (e) => {
console.log(currentOp)
newOperators.push(e.target.innerText);
console.log('topOfOp',newOperators)
display.innerText = '';
if(newOperators.length === 1) {
} else if(newOperators.length === 2) {
console.log(operate(firstNumber,secondNumber,newOperators[1]));
total = operate(firstNumber,secondNumber,newOperators[1]);
display.innerText = total;
firstNumber = total;
secondNumber = 0;
fNumArr = [];
fNumArr.push(total)
sNumArr = [];
}
})
})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Caculator</title>
<link rel="stylesheet" href="styles.css">
<script src="./app.js" defer></script>
</head>
<body>
<h1 class="title">Calculator</h1>
<div class="container">
<div class="calculator">
<div class="display">This will print result</div>
<button class="clear">Clear</button>
<button class="plus operator">+</button>
<button class="minus operator">-</button>
<button class="multiply operator">x</button>
<button class="divide operator">/</button>
<button class="equal ">=</button>
<button class="one number">1</button>
<button class="two number">2</button>
<button class="three number">3</button>
<button class="four number">4</button>
<button class="five number">5</button>
<button class="six number">6</button>
<button class="seven number">7</button>
<button class="eight number">8</button>
<button class="nine number">9</button>
<button class="nought number">0</button>
<button class="period number">.</button>
</div>
</div>
</body>
</html>
In your numbers.forEach loop you made the mistake of:
if( newOperators.length = 1)
You should fix that.
Also, a little advice as you are starting out (I am also starting out WebDev):
You should name your variables clearly even of they are too long.
Refractor your code into functions and files for example make it so you pass in a callback to your event listeners and get rid of repetitive code. Remember keep it DRY (Don't Repeat Your code)

How do I simplify my code by making one addAndSubtract function?

Like the title says, I would like to simplify this JavaScript so that I have one addAndSubtract function for the buttons.
I am quite new and I have no idea how to go about it.
Here is the code:
let add= document.querySelector("#add");
let subtract = document.querySelector("#subtract");
add.addEventListener("click",function(){
let output = document.querySelector("#output");
let result = Number(output.innerText) + 1;
if (result >10){
result = 10;
}
output.innerText = result;
});
subtract.addEventListener("click",function(){
let output = document.querySelector("#output")
let result = Number(output.innerText) - 1;
if (result<0){
result=0;
}
output.innerText = result;
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script defer src="script.js"></script>
<title>Counter</title>
</head>
<body>
<h1>Le Count!</h1>
<div class = "Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
</body>
</html>
You can read the ID of the button being clicked in the handler, and act accordingly. (The switch could be a series of ifs too.)
function handleClick(event) {
const action = event.target.id;
const output = document.querySelector("#output");
let value = parseInt(output.innerText);
switch (action) {
case "add":
value++;
break;
case "subtract":
value--;
break;
}
value = Math.min(10, Math.max(value, 0)); // clamp to 0..10
output.innerText = value;
}
document.querySelector("#subtract").addEventListener("click", handleClick);
document.querySelector("#add").addEventListener("click", handleClick);
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract">-</button><span id="output">0</span><button id="add">+</button>
</div>
Create a single function which takes your result number and add/subtract as parameter.
function eventer(result_param, arithmat){
let output = document.querySelector("#output")
if(arithmat){
let result = Number(output.innerText) + 1;
}else{
let result = Number(output.innerText) - 1;
}
if (result<result_param){
result=0;
}
}
Always try to make your similar code converted to reusable functions and if_else to ternary operators.
You need to create a function as following
function operation(val,maxvalue,minvalue){
let output = document.querySelector("#output")
let result = Number(output.innerText) + val;
if (result<minvalue){
result=minvalue;
}
if (result>maxvalue){
result=maxvalue;
}
output.innerText = result;
}
And use as below
let subtract = document.querySelector("#subtract");
subtract.addEventListener("click",operation.bind(this,-1,10,0))
let add = document.querySelector("#add");
add.addEventListener("click",operation.bind(this,1,10,0))
Let me know if you face any issue
Just add a data attribute to each button that describes the operation that should be performed. Use the same click handler and check the attribute for which operation should be performed.
It's also easier to keep track of the value in a scoped variable too.
let value = 0;
const output = document.querySelector("#output");
const buttons = document.querySelectorAll(".operation");
const operations = {
add: () => value = Math.min(++value, 10),
subtract: () => value = Math.max(--value, 0)
};
const setOutput = () => {
output.innerText = value;
};
// set initial output value
setOutput();
[...buttons].forEach((button) => {
button.addEventListener('click', (e) => {
const operation = e.target.dataset.operation;
let func = operations[operation];
func && func();
setOutput();
});
});
<h1>Le Count!</h1>
<div class="Counter_Container">
<button id="subtract" class="operation" data-operation="subtract">-</button>
<span id="output"></span>
<button id="add" class="operation" data-operation="add">+</button>
<button id="multiply" class="operation" data-operation="multiply">*</button>
</div>

JS Calculator - what is wrong with my code?

EDIT 2: I'm just starting again from scratch. No point in trying to understand these complex problems problems right now when I am a novice. Have consulted someone from my cohort who can go through it with me. I appreciate the advice and insight.
I have been editing this code heavily, as the original relied a constructor. The calculator does not currently append any numbers to either displays when pushed, and I am not sure why! I think the problem lies somewhere in the appending/ node process or the update display function! Any and all advice/ ideas welcomed.
For context I am 5 weeks into a 12 week intensive course and am a baby baby baby coder. Please explain like I am 5!!!
EDIT: If you want to see original code please look at my previous question!
JAVA SCRIPT
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
clear = () => {
currentOperand = "";
previousOperand = "";
operation = undefined;
};
remove = () => {
currentOperand = currentOperand.toString().slice(0, -1);
};
chooseOperation = (operation) => {
if (currentOperand === "") return;
if (previousOperand !== "") {
compute();
}
operation = operation;
previousOperand = currentOperand;
currentOperand = "";
};
compute = () => {
let computation;
const prev = parseFloat(previousOperand);
const current = parseFloat(currentOperand);
if (isNaN(prev) || isNaN(current)) return;
switch (operation) {
case "+":
computation = prev + current;
break;
case "-":
computation = prev - current;
break;
case "*":
computation = prev * current;
break;
case "÷":
computation = prev / current;
break;
default:
return;
}
currentOperand = computation;
operation = undefined;
previousOperand = "";
};
getDisplayNumber = (number) => {
const stringNumber = number.toString();
const integerDigits = parseFloat(stringNumber.split(".")[0]);
const decimalDigits = stringNumber.split(".")[1];
let integerDisplay;
if (isNaN(integerDigits)) {
integerDisplay = "";
} else {
integerDisplay = integerDigits.toLocaleString("en", {
maximumFractionDigits: 0,
});
}
if (decimalDigits != null) {
return `${integerDisplay}.${decimalDigits}`;
} else {
return integerDisplay;
}
};
updateDisplay = () => {
currentOperandTextElement.innerText = getDisplayNumber(currentOperand);
if (operation != null) {
previousOperandTextElement.innerText = `${getDisplayNumber(
previousOperand
)} ${operation}`;
} else {
previousOperandTextElement.innerText = "";
}
};
appendNumber = (number) => {
if (number === "." && currentOperand.includes(".")) return;
currentOperand = currentOperand.toString() + number.toString();
};
equalsButton.addEventListener("click", (button) => {
calculator.compute();
calculator.updateDisplay();
});
numberButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.appendNumber(button.innerText);
calculator.updateDisplay();
});
};
operationButtons.forEach = (button) => {
button.addEventListener("click", () => {
calculator.chooseOperation(button.innerText);
calculator.updateDisplay();
});
};
allClearButton.addEventListener("click", (button) => {
calculator.clear();
calculator.updateDisplay();
});
deleteButton.addEventListener("click", (button) => {
calculator.delete();
calculator.updateDisplay();
});
item = (previousOperandTextElement, currentOperandTextElement) => {
previousOperandTextElement = previousOperandTextElement;
currentOperandTextElement = currentOperandTextElement;
clear();
};
const numberButtons = document.querySelectorAll("[data-number]");
const operationButtons = document.querySelectorAll("[data-operation]");
const equalsButton = document.querySelector("[data-equals]");
const deleteButton = document.querySelector("[data-delete]");
const allClearButton = document.querySelector("[data-all-clear]");
const previousOperandTextElement = document.querySelector(
"[data-previous-operand]"
);
const currentOperandTextElement = document.querySelector(
"[data-current-operand]"
);
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Calculator</title>
<script src="calcedit.js" defer></script>
</head>
<body>
<div class="calculator-grid">
<div class="output">
<div data-previous-operand class="previous-operand"></div>
<div data-current-operand class="current-operand"></div>
</div>
<button data-all-clear class="span-two">AC</button>
<button data-delete>DEL</button>
<button data-operation>÷</button>
<button data-number>1</button>
<button data-number>2</button>
<button data-number>3</button>
<button data-operation>x</button>
<button data-number>4</button>
<button data-number>5</button>
<button data-number>6</button>
<button data-operation>+</button>
<button data-number>7</button>
<button data-number>8</button>
<button data-number>9</button>
<button data-operation>-</button>
<button data-number>.</button>
<button data-number>0</button>
<button data-equals class="span-two">=</button>
</div>
</body>
</html>
So reading through your code, this issue is related to your understanding of your previous question
removing the Class means you no longer have a calculator instance or Object to work with so you can to work in a more procedural way
To start with
const calculator =
(previousOperandTextElement, currentOperandTextElement, operation);
Should be replaced with
var previousOperandTextElement = "",
currentOperandTextElement = "",
operation;
Anywhere you've got calculator for example calculator.compute(); should just be replaced with the new function you've created, in this case compute(); because you don't have a calculator object to work with.
As the previous comments suggested, for this may not be a good approach and a class / prototype approach might be better (what you had originally)

Is there a fix for number counter bug using vanilla javascript

I made products quantity counter for e-commerce that should increase and decrease the quantity by 1 and it works only if the elements exist in dom without appending from javascript
but when I click on the get button to append from javascript the last appended element only increases or decreases by one.
here is the code:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
}
static plusFunc() {
// plus btn
let plus = document.querySelectorAll('.plus');
plus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
});
}
static minusFunc() {
// minus btn
let minus = document.querySelectorAll('.minus');
minus.forEach(function(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
Cart.insertEl();
Cart.plusFunc();
Cart.minusFunc();
});
<button type="button" id="get">get</button>
<main></main>
You're adding a new plus and a new minus listener to each element whenever a new element is appended. Have plusFunc and minusFunc only add to the newly created element instead:
class Cart {
static global() {
Cart.getBtn = document.getElementById('get');
Cart.main = document.getElementsByTagName('main')[0];
Cart.min = 1;
}
constructor(num) {
this.num = num;
}
static insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<br>
<div>
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
</div>
`;
Cart.main.appendChild(div);
return div;
}
static plusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.previousElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num >= Cart.min) {
num1.num += 1;
}
if (num1.num >= max) {
num1.num = max;
}
input.value = num1.num;
});
}
static minusFunc(btn) {
btn.addEventListener('click', function(e) {
let input = e.target.nextElementSibling;
let max = Number(input.getAttribute('max'));
let num1 = new Cart(Number(input.value));
if (num1.num <= max) {
num1.num -= 1;
}
if (num1.num <= Cart.min) {
num1.num = Cart.min;
}
input.value = num1.num;
});
}
}
Cart.global();
// events
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, plus] = div.querySelectorAll('button');
Cart.plusFunc(plus);
Cart.minusFunc(minus);
});
<button type="button" id="get">get</button>
<main></main>
But this quite a weird setup - why have a class that basically has nothing but static methods? Consider a plain object instead:
const Cart = {
getBtn: document.getElementById('get'),
main: document.querySelector('main'),
min: 1,
max: 20,
insertEl() {
const div = document.createElement('div');
div.innerHTML = `
<button type="button" class="minus">-</button>
<input type="number" min="1" max="20" value="1">
<button type="button" class="plus">+</button>
`;
this.main.insertAdjacentHTML('beforeend', '<br>');
this.main.appendChild(div);
return div;
}
}
Cart.getBtn.addEventListener('click', function() {
const div = Cart.insertEl();
const [minus, input, plus] = div.children;
minus.addEventListener('click', () => input.value = Math.max(Cart.min, input.value - 1));
plus.addEventListener('click', () => input.value = Math.min(Cart.max, Number(input.value) + 1));
});
<button type="button" id="get">get</button>
<main></main>

Element text not changing when passing selected textContent and new value to an update function

I'm creating a CRUD page where the user can add, delete and edit text, but I have an issue in updating the text after I select it for edit.
In editText function when I click the edit button the text that was added will pop up inside the input field. When I click on the update button (triggering the updateText function), I can see the text in console log but the corresponding html is not updated.
HTML
<div class="main">
<form>
<input type="text" placeholder="search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">update</button>
</div>
</div>
Javascript
const inputsearch = document.querySelector('form input');
const addInputBtn = document.querySelector('#add');
const update = document.querySelector('#update');
addInputBtn.addEventListener('click', addtext);
function addtext(){
let li = document.createElement('li');
let inputadd = document.querySelector('.add-text');
let addedtext = inputadd.value;
let h1Tag = '<h1 id="text">'+addedtext+'</h1>';
let tags = h1Tag + '<button id="delete">Delete</button><button id="edit">Edit</button>';
if(addedtext == ''){
alert('please add some text');
return;
}else{
li.innerHTML = tags;
document.querySelector('ul').appendChild(li);
}
li.querySelectorAll('#delete')[0].addEventListener('click', deleteText);
li.querySelectorAll('#edit')[0].addEventListener('click', editText);
getlist(li, h1Tag);
inputadd.value = '';
}
function deleteText(e) {
e.target.parentNode.remove();
document.querySelector('.add-text').value = '';
}
function editText(e) {
let currentText = e.target.parentNode.firstChild.textContent;
let currentValue = document.querySelector('.add-text');
currentValue.value = currentText;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText = currentValue.value
console.log(currentText = currentValue.value);
}
}
function getlist(li, h1Tag) {
inputsearch.addEventListener('keyup', serchText);
function serchText(e) {
let typetext = e.target.value.toLowerCase();
if(h1Tag.toLowerCase().indexOf(typetext) != -1){
li.style.display = 'block';
}else{
li.style.display = 'none';
}
}
}
To solve the issue without changing your overall approach, your edit button click needs to get the corresponding element (not just its textContent) and pass it to your getupdate() function to be updated when your update button is clicked. Relatively minor changes to your current functions:
function editText(e) {
const currentText = e.target.parentNode.firstChild;
const currentValue = document.querySelector('.add-text');
currentValue.value = currentText.textContent;
getupdate(currentText, currentValue);
}
function getupdate(currentText, currentValue) {
update.addEventListener('click', updateText);
function updateText() {
currentText.textContent = currentValue.value;
}
}
There are some other issues with your code, particularly the creation of multiple elements with the same id (which is malformed and will likely become problematic as you add additional features). Following is a snippet that addresses that issue as well as simplifying some of your functions and fixing the search.
const search = document.querySelector('form input');
const input = document.querySelector('.add-text');
const container = document.querySelector('ul');
let items = null;
let currentItem = null;
const searchItems = (event) => {
if (items) {
const s = event.currentTarget.value.toLowerCase();
for (const item of items) {
if (item.firstChild.textContent.toLowerCase().indexOf(s) !== -1) {
item.style.display = 'block';
} else {
item.style.display = 'none';
}
}
}
};
const deleteItem = (event) => {
currentItem = null;
event.currentTarget.parentNode.remove();
};
const editItem = (event) => {
currentItem = event.currentTarget.parentNode.firstChild;
input.value = currentItem.textContent;
};
const updateItem = () => {
if (currentItem) {
currentItem.textContent = input.value;
}
};
const addItem = () => {
let val = input.value
if (val) {
const li = document.createElement('li');
let inner = '<h1 class="text">' + val + '</h1>';
inner += '<button class="delete">Delete</button>';
inner += '<button class="edit">Edit</button>';
li.innerHTML = inner;
container.appendChild(li);
val = '';
currentItem = li.firstChild;
items = document.querySelectorAll('li');
for (let del of document.querySelectorAll('.delete')) {
del.addEventListener('click', deleteItem);
}
for (let edit of document.querySelectorAll('.edit')) {
edit.addEventListener('click', editItem);
}
} else {
alert('please add some text');
return;
}
};
search.addEventListener('keyup', searchItems);
document.querySelector('#add').addEventListener('click', addItem);
document.querySelector('#update').addEventListener('click', updateItem);
<div class="main">
<form>
<input type="text" placeholder="Search">
</form>
<ul></ul>
<div>
<input class="add-text" type="text" placeholder="Add Text">
<button id="add">Add</button>
<button id="update">Update</button>
</div>
</div>

Categories