Skip to content

Instantly share code, notes, and snippets.

@craigblunden
Last active July 12, 2016 02:24
Show Gist options
  • Save craigblunden/cc43d9d7576816758c1bd88c39cfc3db to your computer and use it in GitHub Desktop.
Save craigblunden/cc43d9d7576816758c1bd88c39cfc3db to your computer and use it in GitHub Desktop.
Extra Options Dynamic Pricing

Parent Template Script

function updatePricing(extraOptionsPrices){
	if (extraOptionsPrices.length){
		var extraPriceSum = 0;
		for (var i = 0; i < extraOptionsPrices.length; i++){
			extraPriceSum += extraOptionsPrices[i];
		}
	} else {
		var extraPriceSum = 0;
	}

	var productPrice = parseFloat($("#productvalue").val());

	var fullprice = productPrice+extraPriceSum;
	$(".productprice").html($.formatCurrency(fullprice));
}

$(function(){
    // Checks changed element for new price
    $("#_jstl__buying_options").on('change', ".js-extras" ,function(){
		var extraOptionsPrices = [];
		$(".js-extras").each(function(){
			var price = $("option:selected", this).attr('data-cost') || 0;
			if (price){
				extraOptionsPrices.push(parseFloat(price));
			}
		});

		updatePricing(extraOptionsPrices)
  });
});

Buying Options Template

  • add price to individual option
[%if [@price@] > 0 %]data-cost="[%FORMAT type:'number' dp:'2'%][@price@][%/format%]"[%/if%]
  • add js-extras class to select option
[%PARAM *select_option%]
    <tr>
		<td>
			<label>[@name@]</label>
		</td>
		<td>
			<select name="extra[@count@]" class="form-control js-extras" id="productextra[@count@]" rel="[@SKU@]">
			[@choices@]
			</select>
		</td>
	</tr>
[%END PARAM%]
[%PARAM *choices%]
    <option type="text" class="form-control" [%if [@price@] > 0 %]data-cost="[%FORMAT type:'number' dp:'2'%][@price@][%/format%]"[%/if%] value="[@option_id@]">[%nohtml%][@text@][%end nohtml%]
        [%if [@price@] ne '0'%]
            (+ [%FORMAT type:'currency'%][@price@][%END FORMAT%])
        [%/if%]
    </option>
[%END PARAM%]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment