If you use the button inside forEach, only the top one is applied.

Asked 1 years ago, Updated 1 years ago, 282 views

I'm making a shopping basket. I made the list come out using forEach, but I want to implement the quantity button.

 <input class="minusbutton" type='button' onclick='count("minus") value='-'/gt;
 <div id='result'>${list.basket_count}</div>
 <input class="plusbutton" type='button' onclick='count("plus")' value='+'/>

In this way, I set the result value to -1 +1 when I click the minus button or the plus button using JavaScript, and only the value at the top of the shopping cart list is applied. For example, there are three products, and even if you add the number of the third product +, the number of the first product will increase. How do we solve this?!

foreach

2022-10-09 01:00

1 Answers

1. You should look at the window.count() function definition, but... There is a more crucial issue than that. The problem is that the target to count up has id.

In HTML, the id property must appear only once throughout the document.(That would be the identification.) However, your code is likely to be <divid="result"> several times. So no matter how window.count() tries to manipulate document.getElementById('result'), only the first div found with that ID is being manipulated.

Fix it with a class and see if the following code works:

<input class="minusbutton" type='button' onclick="count(this, 'minus')" value='-' />
<div class='result'>0</div>
<input class="plusbutton" type='button' onclick="count(this, 'plus')" value='+' />
var count = function (clickedElement, plusOrMinus) {
  var parent = clickedElement.parentElement;
  var result = parent.querySelector('.result');
  // The following is omitted
};

2. What you're implementing is called a spinner. You have to be able to process the number input, give the raise and lower buttons, and define how many at a time.
But actually, to implement that, it's the neatest to use the step of number type input provided by the latest browsers.
https://www.w3schools.com/tags/att_input_step.asp
If it were me, I would just wear this and pass by.


2022-10-09 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.