I want to create an E-commerce cart where quantity increase or decrease with button, since cart have multiple items so multiple text box and button have same class name. For testing purpose I created 5 text boxes with buttons, one to increment and another one to decrease. When I click any button they only change
var dec = document.getElementsByClassName("dec_button");
var inc = document.getElementsByClassName("inc_button");
var x = document.getElementsByClassName("num");
for (var i = 0; i <= 3; i++) {
dec[i].addEventListener("click", Dec);
inc[i].addEventListener("click", Inc);
function Dec() {
x[i].value -= 1;
}
function Inc() {
x[i].value = +x[i].value + 1;
}
}
<input type="button" class="dec_button" value="-">
<input type="text" value="0" class="num">
<input type="button" class="inc_button" value="+">
<br>
<hr>
<input type="button" class="dec_button" value="-">
<input type="text" value="0" class="num">
<input type="button" class="inc_button" value="+">
<br>
<hr>
<input type="button" class="dec_button" value="-">
<input type="text" value="0" class="num">
<input type="button" class="inc_button" value="+">
<br>
<hr>
<input type="button" class="dec_button" value="-">
<input type="text" value="0" class="num">
<input type="button" class="inc_button" value="+">
<br>
<hr>
<input type="button" class="dec_button" value="-">
<input type="text" value="0" class="num">
<input type="button" class="inc_button" value="+">
<br>
<hr>