Price Variations
So how would one in JavaScript or with the added help of jQuery be able to get price variations. For example the first item is a set base at $450 and every item after that is a add
Solution 1:
Okay, so if I understand you correctly, you want to apply a discount to the given price in a clean manner, depending on the number of items. I'd first start by applying the DRY (Don't Repeat Yourself) principle to your code, and putting variables in local scope:
//var dropResult = $("input[name=drop]:checked").val();//this line doesn't actually do anything, so I removed it. It will always return true, as you're using the :checked pseudo-selector to only select checked checkboxes.
$(function (){
$(".t").click(function(){
dropCalculate(450);
});
});
functiondropCalculate(dropPrice) {
var dropAmount = $(".itemadd", "#items").length,
dropTotal = dropAmount * dropPrice;
if (dropResult != 1) {
dropTotal = dropTotal / 2;
}
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
Which is a lot cleaner. Then, if you have more complex discount rules, or multiple rules for multiple products, you can use an object for that. Here is a simple example of that:
$(function (){
$(".t").click(function(){
var pricesObj = {
'default': 75,
'1':450,
'2':225
};
dropCalculate(pricesObj);
});
});
functiondropCalculate(priceObj) {
var dropAmount = $(".itemadd", "#items").length;
if (priceObj[dropAmount]) {
dropTotal = priceObj[dropAmount] * dropAmount;
}
else{
dropTotal = priceObj['default'] * dropAmount;
}
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
If you need any help understanding that, just ask!
Update: I misunderstood your use case, but this should still point you in the right direction. In my code, if there is 1 product, the price is 450, 2 is 225, and more is 75 each.
Solution 2:
a quick change you could make, it's something like that:
dropTotal = dropAmount * dropPrice;
$("#dropPrice").html("Price Total: $" + dropResult == 1 ? dropTotal.toFixed(2)) : (dropTotal / 2).toFixed(2));
Solution 3:
check this fiddle
$('#dropPrice').text( '$' + (450 + ((450 * ($('#items .itemadd').length - 1)) / 3)) / (Number($("input[name=drop]").is(':checked')) + 1));
Post a Comment for "Price Variations"