Skip to content
Advertisement

how to make multiple counter buttons not interfere with each other

So basically I am making an online restaurant website where you can order food. I am going to make cards for each food item listed. Right now, I am making buttons that add and subtract the number of each item the customer wants to purchase.

JavaScript
JavaScript

How do I get the second button to effect the correct HTML rather than the total of the first item?

Advertisement

Answer

The problem with your code is the point at which you declare your variables, as well as the means by which you select the elements:

JavaScript

Instead, we need to look at which <button> was pressed and from there find the correct menu-item to increment or decrement; so in the following code I’ve taken advantage of EventTarget.addEventListener() to pass a reference to the triggered Event to the function that is bound as the event-listener:

JavaScript
JavaScript
JavaScript

JS Fiddle demo.

References:

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement