I'm trying to increase the decrease the number in the span, when I click - number -1, + number +1. The below is the function I created, one is not working. When I click the - or +, the error shows me that the innerText in (Number(count_i[k].innerText))
and count_i[k].innerText
are not work. the error Uncaught TypeError: Cannot set property 'innerText' of undefined
. I use that in the same file above, also in a for loop and work, why this one is not working? And I did the working one, why that one is working?
Not Working code:
var unit_p = document.getElementsByClassName("unit_price");
var count_i = document.getElementsByClassName("count_item");
var p_btn = document.getElementsByClassName("p_item");
for (var k = 0; k < p_btn.length; k++) {p_btn[k].onclick = function() {
var a = (Number(count_i[k].innerText));
a += 1;
count_i[k].innerText = a;
console.log(a);
}
}
var d_btn = document.getElementsByClassName("d_item");
for (var k = 0; k < d_btn.length; k++) {
d_btn[k].onclick = function() {
var a = (Number(count_i[k].innerText));
if (a > 0) {
a -= 1;
count_i[k].innerText = a;
console.log(a);
}
}
}
Working code:
var unit_p = document.getElementsByClassName("unit_price");
var count_i = document.getElementsByClassName("count_item");
var p_btn = document.getElementsByClassName("p_item");
for (var i = 0; i< p_btn.length; i++) {
(function (i) {
p_btn[i].onclick = function () {
var a = parseInt(count_i[i].innerHTML);
++a;
count_i[i].innerHTML = a;
console.log(a);
get_after_Amount();
}
})(i)
}
var d_btn = document.getElementsByClassName("d_item");
for (var i = 0; i < p_btn.length; i++) {
(function (i) {
d_btn[i].onclick = function () {
var a = parseInt(count_i[i].innerHTML);
if (a != 0) {
--a;
count_i[i].innerHTML = a;
} else {
count_i[i].innerHTML = 0;
}
get_after_Amount();
}
})(i)
}
<div class="col-3"><span style="font-weight: 500;" class="d_item"> - </span><span style="margin:0px 10px" class="count_item">5</span><span class="p_item" style="font-weight: 500;"> + </span></div>