simple material cost calculator - javascript

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>

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.

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.

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>

Related

How to add numbers in a for loop a set amount of times and display on HTML

**Hi, apologies for what some might seem as an easy question as I am quite new to Javascript coding. So here goes...on my html I have three input fields: Duct size, Insulation and Number of Holes. I want to show an array of measurements on the HTML in relation to the amount of holes, insulation and duct size entered. E.g first hole measurement, second hole, third hole etc... however the first measurement is calculated differently to the remaining measurements. Maybe this can clear up the formula and what I want to show on the screen:
1.Enter a measurement in duct size.
2.Enter insulation thickness.
3.Enter number of holes. With this information I want to calculate and display the measurements based off the number of holes and duct size measurement.
Here is an example:
Duct size: 400 mm
Insulation: 50 mm
Number of holes: 4
Insulation(50) * 2 - Duct size e.g 400 - 100 = 300 then 300 / 4 (number of holes) = 75 (want to show this number on HTML as: "Hole spacing = 75 mm ")
For first measurement(first Hole Spacing)=(spacing Of Holes)75 /2 + 50 (insulation) = 87.5 mm(This will be the first measurement to show on DOM).
Then for all other measurements relative (determined by number of holes >element)add spacing Of Holes to first Hole Spacing and display this.
E.g 87.5 + 75 = 162.5 (this is the second hole measurement displayed)
162.5 + 75 = 237.5 (this is the third hole measurement displayed)
237.5 + 75 = 312.5 (this the third hole measurement displayed)**
function ductPitotHoleCalculate() {
var ductSize = document.getElementById("duct-size").value;
var insulation = document.getElementById("insulation").value;
var amountOfHoles = document.getElementById("number-of-holes").value;
//It should multiply insulation by 2 and subtract from ductsize
var subtractInsulation = parseFloat(ductSize) - parseFloat(insulation) * 2;
//It should find the measurement between holes by dividing numberofHoles and subtractInsulation.
var spacingOfHoles = subtractInsulation / parseFloat(amountOfHoles);
//It should use the spacingOfHoles number and divide by 2 and add insulation for first hole and show on DOM
var firstHoleSpacing = spacingOfHoles / 2 + parseFloat(insulation);
// It should use a for loop to parse amountOfHoles and add spacingofHoles to firstHoleSpacing
var newAmount = parseFloat(amountOfHoles) - 2;
var myArray = [];
for (var i = 0; i < newAmount; i + spacingOfHoles) {
myArray.push(firstHoleSpacing + spacingOfHoles);
}
document.getElementById("answer-5").innerHTML = myArray;
}
<section id = "VSD-calculator">
<div id = "pitot-holes">
<h2> Calculate pitot hole duct measurements (type 0 for no insulation)
</h2>
<h2 id="answer-5"></h2>
<input type = "number" id = "duct-size" placeholder="Duct size in
mm"class="mytext">
<input type = "number" id = "insulation" placeholder="Insulation in
mm"class="mytext">
<input type = "number" id = "number-of-holes" placeholder="Number of
Holes"class="mytext">
<button onclick="ductPitotHoleCalculate()"id="calc-button" class = "calc"
>Calculate</button>
</div>
</section>
Thanks to all who helped me, I have solved this now! I think by explaining it and typing it down helped me make sense of it and write the code. I ended up using a while loop instead.
function ductPitotHoleCalculate() {
var ductSize = document.getElementById("duct-size").value;
var insulation = document.getElementById("insulation").value;
var amountOfHoles = document.getElementById("number-of-holes").value;
//It should multiply insulation by 2 and subtract from ductsize
var subtractInsulation = parseFloat(ductSize) - parseFloat(insulation) * 2;
//It should find the measurement between holes by dividing numberofHoles and
subtractInsulation.
var spacingOfHoles = subtractInsulation / parseFloat(amountOfHoles);
//It should use the spacingOfHoles number and divide by 2 and add insulation for
first
hole and show on DOM
var firstHoleSpacing = spacingOfHoles.toFixed(2) / 2 + parseFloat(insulation);
var i = 0;
var strHoles = parseFloat(amountOfHoles);
var myArray = '';
while (i < strHoles) {
myArray += firstHoleSpacing + (i * spacingOfHoles) + ' mm, ' + '<br />';
i++;
}
document.getElementById("answer-5").innerHTML = `Hole spacing = ${spacingOfHoles}
mm
` + '<br />' + myArray;
}

Javascript populating hidden fields on mouseover - Before click

Looking for a solution to another problem I cam across the ability to run javascript on mouseover
I'd like to run this:
$(document).ready(function(){
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
}
When a user mouses over my submit button
When the script runs I'd like it to populate these fields which are then included in the form action
<input type="hidden" name="repay" id="repay_input" value="">
<input type="hidden" name="interest" id="interest_input" value="">
Right now it doesn't seem to work but this may be because I've missed a small thing or it just won't work entirely
Thank you - If anyone has a better idea on how to achieve my aim please let me know, I've tried PHP but no joy
Button for clarity
<button class="col-sm-4 enter-button" type="submit" name="submit" onmouseover="return myPayment()" value="Calculate">Calculate Payments</button>
Update:
I tweaked the javascript and the button but then missed off naming the form to match the reference in the JS
Also my mortgage calculations were WAY off due to the way the form collects % rate
Declare your function outside of jQuery's document.ready wrapper, and your button only needs to look like this:
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
<button onmouseover="myPayment()" ...></button>

Compute the costs depending on the quantity with javascript

I can't seem to finish this. I know how to find out if the number is divisible by 3 but once I get above 3 how do I keep the discount plus the remainder? Example: 7 tickets cost $120
$20 each or 3 for $50
<input id="raffleTix" type="text" value="0" />
if($('#raffleTix').val() % 3 == 0){
raffle = ($('#raffleTix').val() / 3) * 50;
}else if($('#raffleTix').val() < 3){
raffle = $('#raffleTix').val() * 20;
}else{
}
There is no need to have any conditional logic. This can be done with a simple formula:
var value = $('#raffleTix').val();
var setsOfThree = Math.floor(value / 3);
var singles = value - setsOfThree * 3;
raffle = setsOfThree * 50 + singles * 20;
Or even better, it could all be placed in a function so that different values could be passed without modifying the code:
function computeCost(quantity, setSize, setCost, singleCost) {
var sets = Math.floor(quantity / setSize);
var singles = quantity - sets * setSize;
return sets * setCost + singles * singleCost;
}
raffle = computeCost($('#raffleTix').val(), 3, 50, 20);

multiple statements for calculation using Javascript

I am trying to do math with Javascript, it will run calculation from one input (monthly salary) to result (tax) as following:
Deduction from annual income (12000)
here comes the hard part, tax is calculated in different levels, so if annual is between 6500 and 25000, tax should be 10%. And if there is more left after 25000 and less than 40000, tax should be 15% added to the previous 10%, and so on.
EX. if annual is 60000, the math will be like this:
60000 - 12000 = 48000 // deduction
25000 X (10/100) = 2500 // 10% tax on 6500-25000 range
48000 - 25000 = 23000 // first cut 25000
23000 X (15/100) = 3450 // 15% tax on 25000-40000 range
total tax will be 2500 + 3450 = 5950
Code:
<input type=text id="salary">
<div id="total"></div>
<script>
function calc(){
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
// Define Tax brackets
var bracket1 = (10 / 100);
var bracket2 = (15 / 100);
if (net >= 6500){
if ( net >= 6500 && net <= 25000 ) {
var tax1 = (net * bracket1);
}
else if ( net >= 30000 && net <= 40000 ) {
var tax2 = (net * bracket2);
}
var result = (tax1 + tax2) / 12; //monthly tax
document.getElementById('total').innerHTML = result ;
}
</script>
So output comes as NaN, I am not sure if what I have done so far is the right thing or variables inside statement is the problem here.
The algorithm itself seems to be... buggy (you might want to review
it), but, assuming some things myself, this works. Try running it and
see what you can improve.
<html>
<head>
<title>TAX</title>
</head>
<script type="text/javascript">
function calc(){
var result, tax1 = 0, tax2 = 0;
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
// Define Tax brackets
var bracket1 = (10 / 100);
var bracket2 = (15 / 100);
if (net >= 6500) {
if (net >= 6500 && net <= 25000) {
tax1 = (net * bracket1);
}
else if (net >= 30000 && net <= 40000) {
tax2 = (net * bracket2);
}
result = (tax1 + tax2) / 12; // monthly tax
}
document.getElementById('total').innerHTML = result;
console.log(result);
}
</script>
<body>
<input type=text id="salary" onblur="calc();" value="0" />
<div id="total"></div>
</body>
</html>
There was a missing };
using var inside the if declarations is not a common practice, so I declared them in a bigger scope (calc() for this matter);
I assumed the line if (net = 30000 && net <= 40000) was about net >= 30000, but... your call;
The way it is now, either tax1 or tax2 will be setted. One of them will be zero. That's because of the if/else statements, they are confusing.
ps.: also, you might wanna use the parseFloat, as stated by some, considering the 'incoming' is not always an integer;
pps: I added a value="" in the input so it is - somewhat - defined at all times.
With the example given, this code might help you get started on the logic.
function calc(){
var salary = document.getElementById('salary').value;
var annual = salary * 12;
var net = annual - 12000;
console.log(salary, annual, net);
// Define Tax brackets
var bracket1 = (0.1);
var bracket2 = (0.15);
var tax1 = 0;
var tax2 = 0;
var runningNet = net;
if (net >= 6500){
if (net >= 25000) {
tax1 = 2500; // 2500 * 0.10, max tax on bracket 1
runningNet = runningNet - 25000;
tax2 = runningNet * bracket2; // whatever is left over * bracket2
}
else {
tax1 = runningNet * bracket1;
}
var result = (parseFloat(tax1) + parseFloat(tax2));
var monthly = result / 12; //monthly tax
document.getElementById('total').innerHTML = result ;
document.getElementById('monthly').innerHTML = monthly ;
}
}
<input type="text" id="salary" />
<button type="button" onclick="calc()">Calculate</button>
<br/>
Total: <div id="total"></div>
Monthly: <div id="monthly"></div>

Get number value from form, calculation, and updating html content with javascript

I'm trying to make a very simple calculator in HTML and javascript
But it still does not work
My question are:
1. How do I get value from a form and set it as a number, not a string?
2. How do I perform quadratic calculation in javascript?
3. How do I update html content with javascript? So whenever I change the value of the input form and press submit, the result will change based on the input that I type, I've tried the document.getElementById("idhere").innerHTML=valuehere; but still does not work.
<script tyle="text/javascript">
function calculateThis(form) {
var userweight=form.weight.value;
var caffeineamount=form.caffein.value;
var caffeinetimes=form.caffeintimes.value;
var totalcaffeine=caffeineamount*caffeinetimes;
// Calculate max caffeine per person
var maxcaffeine=userweight*10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter=totalcaffeine(1/16);
// Calculating how many hours until the caffeine completely digested
var totaldigest=totalcaffeine;
var digesttime=0;
while (totaldigest>0.05) {
totaldigest=totaldigest(1/2);
digesttime++;
}
digesttime=digesttime*6;
// Calculating when the user will probably die of overdose
var countcaffeine=0;
var overdosetime=1;
while (countcaffeine<maxcaffeine){
countcaffeine=countcaffeine+totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML=totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML=totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML=digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML=overdosetime;
return false;
}
</script>
<form class="form">
Weight<br />
<input type="text" name="weight" class="required" value="" /><p />
Amount of caffein in coffee<br />
<input type="text" name="caffein" class="required" value="" /><p />
How many times drinking coffee in a day<br />
<input type="text" name="caffeintimes" class="required" value="" /><p />
<button type="button" onclick="calculateThis(this.form); return false;">Calculate</button></form>
<h1>Result</h1>
<p id="showtotalkafein">Show Caffein Total Here</p>
<p id="showtotalkafeinsetelah">Show Caffeine Amount After 24 hours</p>
<p id="showwaktudigest">Show Digest TIme Here</p>
<p id="showberapakali">Show Overdose Time Here</p>
function calculateThis(form) {
var userweight = parseInt(form.weight.value, 10);
var caffeineamount = parseInt(form.caffein.value, 10);
var caffeinetimes = parseInt(form.caffeintimes.value, 10);
var totalcaffeine = caffeineamount * caffeinetimes;
console.log(totalcaffeine)
// Calculate max caffeine per person
var maxcaffeine = userweight * 10;
// Calculate remaining after 24 hours
// Half life = 6 hours
var totalcaffeineafter = totalcaffeine * (1 / 16);
// Calculating how many hours until the caffeine completely digested
var totaldigest = totalcaffeine;
var digesttime = 0;
while (totaldigest > 0.05) {
totaldigest = totaldigest * (1 / 2);
digesttime++;
}
digesttime = digesttime * 6;
// Calculating when the user will probably die of overdose
var countcaffeine = 0;
var overdosetime = 1;
while (countcaffeine < maxcaffeine) {
countcaffeine = countcaffeine + totalcaffeine;
overdosetime++;
}
// Show total amount of caffeine
document.getElementById("showtotalkafein").innerHTML = totalcaffeine;
// Show amount of caffeine after 1 day
document.getElementById("showtotalkafeinsetelah").innerHTML = totalcaffeineafter;
// Show digest time
document.getElementById("showwaktudigest").innerHTML = digesttime;
// Show overdose
document.getElementById("showberapakali").innerHTML = overdosetime;
return false;
}
DEMO
Note
Here I used .parseInt() which used to convert a number to integer, if you need any value in Float then use .parseFloat()`.
Problems in your code
form.weight.value, form.caffein.value ... give value as string, so you need to convert them to number (integer/ float).
you used totalcaffeine(1 / 16) and totaldigest = totaldigest(1 / 2);, not a valid Math operation in javascript, it should be totalcaffeine * (1 / 16) and totaldigest = totaldigest * (1 / 2);
According to your comment
What .parseInt(form.caffeintimes.value, 10), do?
Format of parseInt is:
.parseInt(valueToConvert, [radix]).
So, .parseInt(form.caffeintimes.value, 10) will convert form.caffeintimes.value string to a 10-base integer.
Related refs:
.parseInt()
.parseFloat()

Categories