Search code examples
javascripthtmlselectshopping-cart

How to use the value in a select option just once?


I'm building an online shop. From the dropdown the end user picks one option in the select option, and then the price of that option is added to the main price.

<div id='custom-price'>1000</div>

<select id="capsize-price" onchange="changePri()" name="capsize-price">
 <option value='100'>100</option>
 <option value='700'>700</option>
</select>

  function changePri() {
   var customPrice = parseFloat(document.querySelector("#custom-price").textContent);
   var capsizePrice = document.querySelector("#capsize-price").value;

   var price = customPrice + capsizePrice;
   document.querySelector("#custom-price").textContent = price;
  }

I've got that alright, but then I noticed that the price keeps adding. For example, if the end user selects only option 1(100) first, and then later selects only option 2 (700) it adds the price of both.

I know this is what it is supposed to do based on my code but I am struggling to come up with logic on how to just add option 1 when the user selects that and then add just option 2 when the user selects option 2 instead of what it is doing right now.

Any help is appreciated.


Solution

  • Your logic here is making it impossible to know what the original price was once the user has selected a capsize-price. You need to store the original value of custom-price somewhere and use it when generating the final price. For example:

    <div id='original-price'>1000</div>
    <div id='custom-price'></div>
    
    <select id="capsize-price" onchange="changePri()" name="capsize-price">
     <option value='100'>100</option>
     <option value='700'>700</option>
    </select>
    
      function changePri() {
       var originalPrice = parseFloat(document.querySelector("#original-price").textContent);
       var capsizePrice = document.querySelector("#capsize-price").value;
    
       var customPrice = originalPrice + capsizePrice;
       document.querySelector("#custom-price").textContent = customPrice;
      }