I am trying to code a calculator which will give me a cost per square metre.
At the moment, I have the calculator working and producing a cost for the square meterage, however, what I want to try and do is have if statements, so that if the area comes back less than 15 m², the cost is worked out (area * 2000) and if the area comes back more than 15 m² it is worked out as (area star * 1750)
Any help would be greatly appreciated.
My code is currently
function calculateCost() {
var width = document.getElementById("width").value;
var depth = document.getElementById("depth").value;
var area = width * depth;
var totalCost = area * 2000
document.getElementById("result").innerHTML = "Total cost: £" totalCost;
}
<form>
Width in Metres: <input type="text" id="width"><br> Depth in Metres: <input type="text" id="depth"><br>
<input type="button" value="Calculate" onclick="calculateCost()">
</form>
<div id="result"></div>
CodePudding user response:
Instead of
var totalCost = area * 2000
write
var totalCost = area * (area <= 15 ? 2000 : 1750);
Now you will have price = area * 2000 for area less or equal than 15, and discount for higher areas.
CodePudding user response:
You need just to add a condition on the area value:
function calculateCost() {
var width = document.getElementById("width").value;
var depth = document.getElementById("depth").value;
var area = width * depth;
var totalCost = (area < 15) ? area * 2000 : area * 1750;
document.getElementById("result").innerHTML = "Total cost: £" totalCost;
}
<form>
Width in Metres: <input type="text" id="width"><br> Depth in Metres: <input type="text" id="depth"><br>
<input type="button" value="Calculate" onclick="calculateCost()">
</form>
<div id="result"></div>
CodePudding user response:
A few answers were giving using the ternary operator, which were short and succinct, but I would argue they're not the most readable.
Effectively, you have a number (be it 2000 or 1750) that you need to multiply your the area with to get your total cost. You could start off by giving this a name. Say, costMultiplier
.
We can assign it with the value 2000 to begin with (which assumes the area is less than 15m2).
var costMultiplier = 2000;
Now, you just need to check if the area is greater than 15m2. And if it is, you update costMultiplier
accordingly.
if (area > 15) {
costMultiplier = 1750;
}
Finally, you can update your totalCost
like this
var totalCost = area * costMultiplier
If there are any other conditions under which the cost multiplier might change, you could just add an else if
branch to the if statement.