I am trying to write a block with prices in which the price per unit of goods changes depending on its quantity. Something like that:
Quantity - Price per unit 1______________________1 ₽ 10_____________________105 ₽ 20_____________________100 ₽ ... Number of goods:__ Total: Unit price:
There is a need to write an input field in which the user enters the quantity of goods, and all this is recalculated and summed up on the fly.
Here is my implementation:
var price1 = 110, price2 = 105, price3 = 100, qty1 = 1, qty2 = 10, qty3 = 20; function conversion(val) { var div = document.getElementById("div"), price = document.getElementById("price"); if (isNaN(val)) { div.innerHTML = ""; price.innerHTML = ""; } else { switch (true) { case (val <= 0): { div.innerHTML = ""; price.innerHTML = ""; break; } case (val >= qty1 && val < qty2): { div.innerHTML = val * price1; price.innerHTML = price1; break; } case (val >= qty2 && val < qty3): { div.innerHTML = val * price2; price.innerHTML = price2; break; } case (val >= qty3): { div.innerHTML = val * price3; price.innerHTML = price3; break; } } } } <div> <div>1 шт. — 110 ₽</div> <div>10 шт. — 105 ₽</div> <div>20 шт. — 100 ₽</div> </div> <div> Количество товаров: <div> <input id="txt" onblur="conversion(this.value)" onchange="conversion(this.value)" onkeypress="conversion(this.value)" onkeyup="conversion(this.value)" type="number"> </div> </div> <div> Итого: <div id="div"></div> </div> <div> Цена за шт.: <div id="price"></div> </div> I ask you to suggest how this can be correctly implemented, given that the lines with the number and price per unit can be from one to infinity (the values are taken from the base). It comes to mind to record the price and quantity in the data artifacts and somehow sort through these lines with the script.
... <div data-quantity="1" data-price="115" id="shop"> <span class="quantity">1</span> <span class="price">115</span> </div> ... Thank!