I would rewrite the checkOptions
and checkAccomp
functions and remove all these if
statements using this pattern: create an object that stores the id of each checkbox and its corresponding price, and then use a for-in
loop with key value lookup, like this:
var OptionPricing = {
'pack11049': 1049,
'pack21199': 1199,
'pack31199': 1199,
'pack41299': 1299,
'pack61499': 1499
};
var AccompPricing = {
0: 0,
1: 129,
2: 258,
3: 1057,
4: 1856
};
function checkOptions() {
var Price = 0;
for (Packs in OptionPricing) {
if ($('#' + Packs).is(':checked')) {
Price += OptionPricing[Packs];
}
}
return Price;
}
function checkAccomp() {
var Accomp = parseInt($('#HowMany').val(), 10);
return AccompPricing[Accomp];
}
function updateTotal() {
var ThePrice = checkOptions() + checkAccomp();
$('#TotalPrice').text(ThePrice);
}
$(function () { $('.DoPricing').click(updateTotal); });
Here's the working jsFiddle. I didn't add all the ids and corresponding prices to the OptionPricing object but you get the idea. Also, if the prices change, or if new prices are added, this pattern should be easier to maintain, not to mention that the code is considerably reduced to just a few lines (and could even be reduced a bit further if you like terse syntax). I used jQuery (you had the tag in the question) but you could easily modify it and use plain js if needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…