Hi I'm new to JS and bootstrap, I'm trying to make a set of buttons under certain condition, in this case, if the item-quantity > 3, then the related plus button will be disabled. However, it didn't work as expected, if I clicked the first plus button, it will disable the thrid one. I also attched a image to illustrate this problem below.
var plusCartItemButtons = document.getElementsByClassName("plus");
for (var i = 0; i < plusCartItemButtons.length; i++) {
var buttonp = plusCartItemButtons[i];
buttonp.addEventListener('click', (event) => {
var buttonClicked = event.target;
var quantityElement = buttonClicked.parentElement.getElementsByClassName("item-quantity")[0];
if (parseFloat(quantityElement.innerText) < 3) {
quantityElement.innerText = parseFloat(quantityElement.innerText) + 1;
// updateCartTotal();
} else {
buttonp.classList.add('disabled');
}
})
}
.disabled {
background-color: red;
}
<div class="cart-items">
<div class="row cart-row" id="cart-row2">
<div class="col-4 border-bottom">
<div class="cart-item-img"><img src="assets/vegetable.jpg" style="width:100px"></div>
<span class="cart-item-title">Vegetable</span>
</div>
<div class="col-4 border-bottom">
<div class="price">$16</div>
</div>
<div class="col-4 border-bottom">
<div class="box">
<button class="btn btn-danger btn-sm minus">-</button>
<span class="item-quantity">1</span>
<button class="btn btn-danger btn-sm plus">+</button>
<button class="btn btn-danger btn-sm delete">Delete</button>
</div>
</div>
</div>
<div class="row cart-row" id="cart-row2">
<div class="col-4 border-bottom">
<div class="cart-item-img"><img src="assets/asparagus.jpg" style="width:100px"></div>
<span class="cart-item-title">Asparagus Steak</span>
</div>
<div class="col-4 border-bottom">
<div class="price">$20</div>
</div>
<div class="col-4 border-bottom ">
<div class="box">
<button class="btn btn-danger btn-sm minus">-</button>
<span class="item-quantity">1</span>
<button class="btn btn-danger btn-sm plus">+</button>
<button class="btn btn-danger btn-sm delete">Delete</button>
</div>
</div>
</div>
<div class="row cart-row" id="cart-row3">
<div class="col-4 border-bottom">
<div class="cart-item-img"><img src="assets/breakfast.jpg" style="width:100px"></div>
<span class="cart-item-title">Breakfast</span>
</div>
<div class="col-4 border-bottom">
<div class="price">$12</div>
</div>
<div class="col-4 border-bottom">
<div class="box">
<button class="btn btn-danger btn-sm minus">-</button>
<span class="item-quantity">1</span>
<!--use span than div to keep them inline-->
<button class="btn btn-danger btn-sm plus">+</button>
<button class="btn btn-danger btn-sm delete">Delete</button>
</div>
</div>
</div>
</div>
Problem image
As illustrated above, I applied the for loop and if statement, then the classList.add() to make this function, but it didn't work as expected. Could anyone help me with this problem? I'll be really appreciate your help.