Tyssen
Tyssen

Reputation: 1711

Combine values of selects to achieve total price

I'm working on a site where you can choose the size of top and/or bottoms and the price is calculated based on what you choose. Prices for all sizes are the same, but the price varies depending on whether you have a single top or bottom or both items selected.

So in the example below, the result should be $130 if you choose just a top or bottom, $260 if you choose both, or 0 if you set both selects back to the default option again.

HTML

<label for="size_top">Select Size (Bikini Top)</label>
<select name="size_top" id="size_top" data-price="130">
  <option value="" data-multiplier="0">--</option>
  <option value="6" data-multiplier="1">Size 6</option>
  <option value="8" data-multiplier="1">Size 8</option>
  <option value="10" data-multiplier="1">Size 10</option>
  <option value="12" data-multiplier="1">Size 12</option>
</select>
<label for="size_btm">Select Size (Bikini Bottom)</label>
<select name="size_btm" id="size_btm" data-price="130">
  <option value="" data-multiplier="0">--</option>
  <option value="6" data-multiplier="1">Size 6</option>
  <option value="8" data-multiplier="1">Size 8</option>
  <option value="10" data-multiplier="1">Size 10</option>
  <option value="12" data-multiplier="1">Size 12</option>
</select>

JS

var basePrice = price = multiplier = 0;

$("select").on("change",function(){

  basePrice  = parseInt($(this).data("price"));
  multiplier = parseInt($(this).find(":selected").data("multiplier"));

  $("select").each(function() {
    price += basePrice * multiplier;
  });

  $(".price").text(price);

});

What's happening though is that when you first change a select, the value is 390 and then whenever you select a value where the multiplier isn't 0, it gets added on to the total, so it just keeps going up.

If I change to price = basePrice * multiplier I get the correct value but just for one select.

Upvotes: 1

Views: 40

Answers (1)

Jain
Jain

Reputation: 1249

Try this

$("select").on("change",function(){

  basePrice  = parseInt($(this).data("price"));
  multiplier = parseInt($(this).find(":selected").data("multiplier"));

  basePrice2  = parseInt($('#size_btm').data("price"));
  multiplier2 = parseInt($('#size_btm').find(":selected").data("multiplier"));
var fp = basePrice  * multiplier  + basePrice2  * multiplier2 ;
  $(".price").text(fp);

});

Upvotes: 1

Related Questions