javascriptmath

Javascript - Adjust price when changing quantity


I have a form to add product to basket where the user need to select quantity. I'm trying to adjust the price when quantity is modified. Here's my code:

  <script>
  function increaseValue() {
    var value = parseInt(document.getElementById('quantity').value, 10);
    value = isNaN(value) ? 0 : value;
    value++;
    document.getElementById('quantity').value = value;
  }
  
  function decreaseValue() {
    var value = parseInt(document.getElementById('quantity').value, 10);
    value = isNaN(value) ? 0 : value;
    value < 1 ? value = 1 : '';
    value--;
    document.getElementById('quantity').value = value;
  }
  </script>

  <div class="quantity-container">
  <span>1</span> 
 <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value">-</div> 
<input type="number" id="quantity" name="quantity" value="1" />
<div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value">+</div>
</div>

I need to adjust the price for the following scenarios:

The problem is that the price is displayed using html between the numbers so i'm confused how to update the price. I assume I will have to use RegEx? I can't just hardcode the base price ($15.49 in this example) because the price is never the same (the prices come from SQL DB)

<div id="product-price">
$15<sup>.49</sup>
</div>

Solution

  • Use ES6's Template literals (``). Try the following:

    For more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

    function increaseValue() {
      var value = parseInt(document.getElementById('quantity').value, 10);
      value = isNaN(value) ? 0 : value;
      value++;
      document.getElementById('quantity').value = value;
      price = '$'+`<span>${p * value}</span>`;
      document.getElementById('product-price').innerHTML=price;
    }
    
    function decreaseValue() {
      var value = parseInt(document.getElementById('quantity').value, 10);
      value = isNaN(value) ? 0 : value;
      value < 1 ? value = 1 : '';
      value--;
      document.getElementById('quantity').value = value;
      price = '$'+`<span>${p * value}</span>`;
      document.getElementById('product-price').innerHTML=price;
    }
    var p='15.49';
    var price = '$'+`<span>${p}</span>`;
    document.getElementById('product-price').innerHTML=price;
    <div id="myDiv">
      <div class="quantity-container">
      <span>1</span> 
      <div class="value-button" id="decrease" onclick="decreaseValue()" value="Decrease Value">-</div> 
      <input type="number" id="quantity" name="quantity" value="1" />
      <div class="value-button" id="increase" onclick="increaseValue()" value="Increase Value">+</div>
    </div>
    
    <div id="product-price">
    
    </div>