CVE
CVE

Reputation: 171

How to create multiple variables dynamically that can be summed up

I have a variable that gets its value once an ID is clicked, via .innerText

var currentID = e.target.id;

I need the value of this variable, currentID, to be stored in a new variable which is named just like the ID of which it got its value.

So, if a user clicks an element with the ID price1, and the price is 200. A new variable with the name price1 with value 200 should be created.

Then, I want to sum up the new variables: price1+price2+price3 etc = totalprice.

This is what I'm doing right now:

$('div.unselected-option').click(function(e) {
   $(this).toggleClass("selected-option unselected-option")

if ($(this).hasClass("selected-option")) {
   var currentID = e.target.id;
   console.log(currentID);
   var price1 = document.getElementById(currentID).innerText

   var finalprice
   finalprice = +price1;
   document.getElementById("showprice2").innerHTML = finalprice

Here's an image of the design:

Here's an image of the design

I can't seem to figure this out... What I'm doing right now just results in having 1 variable which means I cannot sum anything up... I would love your view on this issue!

Upvotes: 0

Views: 212

Answers (1)

Alexandre Nicolas
Alexandre Nicolas

Reputation: 1949

Your use case is pretty strange I hope your backend is secured and well made.

Here is a potential solution:

<div id="a1" onclick="handleProductClick">20</div>
<div id="a2" onclick="handleProductClick">40</div>
<div id="b1" onclick="handleProductClick">20</div>
<div id="b2" onclick="handleProductClick">60</div>
...
<div id="total-price">0</div>
...
const basket = {}

function addToBasket(event) {
  const { id, innerText } = event.target
  const price = parseInt(innertText, 10)
  const product = basket[id] 
  const count = product.count || 1
  basket[id] = {
    price,
    count
  }
}

function getBasketTotalPrice = () => {
  return Object.keys(basket)
   .reduce((total, product) => total + product.count * product.price, 0)
}

function handleProductClick = (event) => {
  addToBasket(event)
  const totalPrice = getBasketTotalPrice()
  document.querySelector('#total-price').innerHTML = totalPrice
}

Upvotes: 1

Related Questions