I have a problem with merging list of nodes values into one array. I would like to have one array of values and update it when buttons are clicked.
I used method forEach and then function where I nested Array.from() method. I obtained a few arrays which amount is depended how many nodes I have.
html code:
<li>
<button class="add">+</button>
<span class="amount" id = "amount0">0</span>
<button class="substract">-</button>
</li>
<li>
<button class="add">+</button>
<span class="amount" id = "amount1">0</span>
<button class="substract">-</button>
</li>
and so on...
JS code:
function addAmount(el) {
let amountElement, adjustAmount;
if (el.classList.contains("add")) {
adjustAmount = 1;
amountElement = el.nextElementSibling;
} else {
adjustAmount = -1;
amountElement = el.previousElementSibling;
}
if (amountElement.innerText >= 0) {
amountElement.innerText =
parseInt(amountElement.innerText) + adjustAmount;
} else {
amountElement.innerText = 0;
}
}
function ordered() {
const amount = document.querySelectorAll(".amount");
amount.forEach(function(order) {
let myArrays = Array.from(order.innerText);
console.table(newArrays);
console.log(order);
});
}
document.addEventListener("click", ordered);
document.addEventListener('click', e => {
if (e.target.tagName == "BUTTON") {
addAmount(e.target);
} else {
console.log(e.target.tagName);
}
});
This code return in console two nodes
<span class="amount" id = "amount">0</span>
and two arrays:
["0"]
which updating. However if number of value is more than 10 the arrays start to divide number of tens and number of unities into two items in array, like:
["1","0"]
but I want to get one item ["10"]. Values of nodes are updating properly.
function addAmount(el) {
let amountElement, adjustAmount;
if (el.classList.contains("add")) {
adjustAmount = 1;
amountElement = el.nextElementSibling;
} else {
adjustAmount = -1;
amountElement = el.previousElementSibling;
}
if (amountElement.innerText >= 0) {
amountElement.innerText =
parseInt(amountElement.innerText) + adjustAmount;
} else {
amountElement.innerText = 0;
}
}
function ordered() {
const amount = document.querySelectorAll(".amount");
amount.forEach(function(order) {
let myArray = Array.from(order.innerText);
console.log(myArray);
console.log(order);
});
}
document.addEventListener("click", ordered);
document.addEventListener('click', e => {
if (e.target.tagName == "BUTTON") {
addAmount(e.target);
} else {
console.log(e.target.tagName);
}
});
<li>
<button class="add">+</button>
<span class="amount" id = "amount0">0</span>
<button class="substract">-</button>
</li>
<li>
<button class="add">+</button>
<span class="amount" id = "amount0">0</span>
<button class="substract">-</button>
</li>
<>.