Reputation: 1383
Okay so i asked this question yesterday and revised it based on the direction i was pointed. It works the way i want it when there are items in the list but, when there is 0 it evals to false so the or kicks in no mater what. I don't want that i need it to show 0.00 when the item count is at 0. I know that 0=false that's why or kicks in. Any help/workaround?
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate();
});
});
function dropCalculate() {
var pricesObj = {
'0':0,
'1':450
};
var dropAmount = $(".itemadd", "#items").length;
$("#dropAmount").html("Total: " + dropAmount);
if (dropResult == 1) {
dropTotal = (pricesObj[dropAmount] * dropAmount) || 450 + (150 * dropAmount - 150);
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else {
dropTotal = (pricesObj[dropAmount] * dropAmount / 2) || 225 + (75 * dropAmount - 75);
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}
}
Upvotes: 1
Views: 86
Reputation: 2904
You might get a better response over at the Code Review Stack Exchange on questions where you don't have an immediate problem, but feel that you could improve your code design.
The following code should do the same thing as the code in your example, but I think it's more readable. An object doesn't seem to be necessary for this use case, but may be useful in the future.
Again, I applied the DRY Principle, and this time I removed Magic Numbers(numbers in the code with no immediately clear meaning).
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate(450);
});
});
function dropCalculate(fullPrice) {
var halfPrice = fullPrice / 2,
quarterPrice = halfPrice / 2,
dropAmount = $(".itemadd", "#items").length,
finalPrice = 0.00;
if(dropAmount > 0){
if (dropResult === 1) {
finalPrice = fullPrice; //the rest of this line was not necessary, as dropAmount - 1 is always 0 here.
} else {
finalPrice = halfPrice + (quarterPrice * (dropAmount - 1));
}
}
$("#dropAmount").html("Total: " + dropAmount);
$("#dropPrice").html("Price Total: $" + finalPrice.toFixed(2));
}
Upvotes: 1
Reputation: 1383
I solved my problem this way. I didn't want to go this route because i felt there was a simpler way.
var dropResult;
$(function (){
$(".t").click(function(){
dropResult = $("input[name=drop]:checked").val();
dropCalculate();
});
});
function dropCalculate() {
var dropAmount = $(".itemadd", "#items").length;
$("#dropAmount").html("Total: " + dropAmount);
if (dropResult == 1 && dropAmount > 0) {
dropTotal = 450 + (150 * (dropAmount -1));
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else if (dropAmount > 0) {
dropTotal = 225 + (75 * (dropAmount -1));
$("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
}else {
$("#dropPrice").html("Price Total: $" + (0.00).toFixed(2));
}
}
Upvotes: 1