Multiple calculations and targeted output in javascript - javascript

As a learning exercise and to also create a simple, but helpful little tool (for me), I am trying to create a web-based form that will take price and quantity data for multiple items and then produce a "per unit cost" (price divided by item quantity). Based on that info, I then want further calculations to provide a final cost based on the cost totals for several unit costs of those items. I have this simple little tool built in an Excel spreadsheet, but I want it in web format also.
I am into shooting as a hobby and I reload my own ammo. This tool takes the bulk price/quantity for four items; bullets, powder, primers, and brass cases, gives the per unit cost and then will tell me the cost per round of ammo (first iteration is the most expensive as new brass casing costs are included), then subsequent loadings (selectable number) is calculated using only bullet, powder, and primer cost since the brass can be reloaded multiple times.
I have the initial start with the html displaying two lines of user input, first line is: bullet, price, quantity, unit. Second line is Powder, price, quantity, unit. The form input is formatted using css grid.
I have a script that works to do the calculations for the first line for the bullet, but I don't know how to get it to reiterate and then calculate and output the powder data. I've read numerous sites concerning form calculations and most if it went right over my head. Some help with this would be appreciated.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>
Ok, the suggestion by Ayaz does work, sort of. I swear I tried that before and it did not. I even still have the old copy where I tried it, I just went back and it doesn't work, but for some reason editing the current working copy, with the exact same code, it works. Sigh, anyway...I've also figured out the code to get and calculate the powder data and it too works.
The formula for the powder unit cost is different than for bullets. Bullets are sold in quantity counts, 50, 100, etc. Powder is sold by weight, typically in 1lb or 8lb containers. However, for calculating per cartridge loading costs there is a second weight unit used, "grains." There are 7000 grains to 1lb. So, the formula I am trying to use for powder is
(pprice*0.06+pprice)/(pquantity*7000)
The 0.06 is there to add in the cost of sales tax. Quantity is entered by the user in pounds, the formula converts it to grains, or is supposed to. When I use that formula, I get weird results. When I run the script with a powder price of 29.99, quantity of 1, it gives me an output of 32. Something is obviously not calculating correctly.
So, I changed the formula to
(pprice*0.06+pprice)/pquantity
and instead of entering 1 for the quantity, I can put in the total grains instead of pounds (7000 for 1lb of powder or 56000 for 8lbs), which is fine since it will always be one or the other.
I then ran into an issue of result precision. The output was only to 4 decimal places on the powder. I needed that output to go to out as far as possible. Since a single grain of powder is incredibly small in terms of price, it seems immaterial, but will be important later when calculating per cartridge prices and especially when calculating multiples of cartridges, such as 20 rounds per "box." The same is true for primers as they come in boxes of 1000. I then tried adding:
return pcost.toPrecision(8);
but that did not change anything. So after adding more fields for primers and brass and playing around, I found that the code line
return bcost,toPrecision(2);
was the culprit. By removing the ".toPrecision" portion, everything returns out to however many decimals it actually calculates to.
On to the next step, now to have it do more math and output the cost of a single, complete round by adding the unit cost for each item together (and then round it up to 2 decimals). Going to go try working on that now...I'll probably have more questions on this..
Here's the current working code:
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
pprice = parseFloat(pprice);
pquantity = parseFloat(pquantity);
pcost = (pprice*0.06+pprice)/pquantity;
prprice = parseFloat(prprice);
prquantity = parseFloat(prquantity);
prcost = (prprice*0.06+prprice)/prquantity;
brprice = parseFloat(brprice);
brquantity = parseFloat(brquantity);
brcost = (brprice*0.06+brprice)/brquantity;
return bcost;
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
this.prunit.value = calculateUnitCost(this.prprice.value, this.prquantity.value);
this.brunit.value = calculateUnitCost(this.brprice.value, this.brquantity.value);
return false;
};
}
}());

Use the below code if Per Unit calculation formula is same for Powder.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06+bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>

Related

How to change value inside textfield HTML

How can I change the value inside my Revenue textfield by subtracting the Cost of Good value from the Sales Price value? I have attached an image of what it looks like currently, but I want to change whats displayed inside my Revenue field after I edit the previous 2 text fields. I have also attached my code.
See attached image
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Add (keyup)="getRev()" to your Sales Price and Cost of Goods inputs.
<div class="product-section">
<h3>
<b>{{ product.productLabel }}</b>
</h3>
<label for="sales-price">Sales Price: </label>
<br>
<input
type="text"
[(ngModel)]="product.salesPrice"
(keyup)="getRev()"
name="sales-label"
placeholder="Enter Sales Price"
/>
<p></p>
<label for="cogs">Cost of Good: </label>
<br>
<input
type="text"
[(ngModel)]="product.cogs"
(keyup)="getRev()"
name="cogs-label"
placeholder="Enter Cogs"
/>
<p></p>
<label for="rev">Revenue: </label>
<br>
<input
type="text"
[(ngModel)]="product.rev"
name="rev-label"
readonly
/>
</div>
Then add a function to your component's typescript file to handle the revenue calculation.
getRev() {
this.product.rev = this.product.cogs - this.product.salesPrice;
}
Can you post the body of getRev()? And, take the quotes away from getRev() so that it calls the function instead of sets the value as the literal string 'getRev()'
Edit:
Is there a way to just subtract the cogs value from my sales value?
Yes, you could use an onchange handler. Here is an example, assuming you set the ID of the three elements as 'cogs', 'sales', and 'revs':
const cogs = document.getElementById('cogs');
const sales = document.getElementById('sales');
const revs = document.getElementById('revs');
cogs.addEventListener('input', (event) => {
const salesNumber = Number(sales.value);
const cogsNumber = Number(cogs.value);
const difference = salesNumber - cogsNumber;
revs.value = difference;
});

Parse float and button click

Having issues using a parsefloat to calculate user entered values. I've looked at my code again and again but can't determine where the error is occuring. When I click the button nothing is displaying as expected.
I have reviewed the code and the naming/id attributes of the variables.
<html>
<head>
<title> Lab 4 Grade Calculator </title>
</head>
<body>
<h2> Grade Calculation</h2>
<p>
Enter your name: <input type="text" id="nameBox" size=12 value=""><br><br> Homework average: <input type="text" id="homeworkBox" value=""><br><br> Lab Average: <input type="text" id="labBox" value=""><br><br> Midterm Average: <input type="text" id="midtermBox"
value=""><br><br> Final Exam score: <input type="text" id="examBox" value=""><br><br>
</p>
<br>
<!-- Start input button -->
<input type="button" value="Calculate Course Grade" onclick="homework=parseFloat(document.getElementById('homeworkBox').value);
labs=parseFloat(document.getElementById('labsBox').value);
midterm=parseFloat(document.getElementById('midtermBox').value);
finalexam=parseFloat(document.getElementById('examBox').value);
overall_Average = homework*0.25 + Labs*0.20 + midterm*0.25 + finalExam*0.30;
document.getElementById('outputDiv').innerHTML = 'Hello '+ document.getElementById('nameBox').value+ ', your overall course average grade is: ' + overall_Average;">
<!-- Close input button -->
<hr>
<br><br>
<div id="outputDiv"></div>
</body>
</html>
The expected result is to calculate the users input values and display them on screen.
You have a few issues that need to be resolved:
Javascript is case sensitive, this means that when you declare a variable with all lowercase letters (eg: labs) you need to reference it using all lower case letters (ie: Labs is not the same as labs). You need to fix this within your code.
You need to get the exact id that you're specifying in your HTML in your JS for your code to work:
document.getElementById('labsBox').value
The above should be labBox, not labsBox, as your id is labBox.
Don't write all your javascript in the onclick method callback, write your javascript in <script> tags or in a separate file which you can then call a function to run your code. This way, you can keep your mark-up (the page structure "code") separate from your logic.
When you're not writing HTML to your page, it's better to use textContent instead of innerHTML
See example below:
function calculateGrade() {
var homework = parseFloat(document.getElementById('homeworkBox').value);
var labs = parseFloat(document.getElementById('labBox').value);
var midterm = parseFloat(document.getElementById('midtermBox').value);
var finalexam = parseFloat(document.getElementById('examBox').value);
var overall_Average = homework * 0.25 + labs * 0.20 + midterm * 0.25 + finalexam * 0.30;
document.getElementById('outputDiv').textContent = 'Hello ' + document.getElementById('nameBox').value + ', your overall course average grade is: ' + overall_Average;
}
<html>
<head>
<title> Lab 4 Grade Calculator </title>
</head>
<body>
<h2> Grade Calculation</h2>
<p>
Enter your name: <input type="text" id="nameBox" size=12 value=""><br><br> Homework average: <input type="text" id="homeworkBox" value=""><br><br> Lab Average: <input type="text" id="labBox" value=""><br><br> Midterm Average: <input type="text" id="midtermBox"
value=""><br><br> Final Exam score: <input type="text" id="examBox" value=""><br><br>
</p>
<br>
<!-- Start input button -->
<input type="button" value="Calculate Course Grade" onclick="calculateGrade()">
<!-- Close input button -->
<hr>
<br><br>
<div id="outputDiv"></div>
</body>
</html>
so many wrong with your variable java declaration has a case-sensitve
you need to check it before you use

Having Trouble Figuring this code out with if else statements for radio buttons

Hey guys I am having trouble with this
please click that for the instructions.Image did not load in for some reason.
This is my current code, honestly I am confused and dont really know how to approach this. I am new to javascript and was trying to do this as practice for an upcoming exam. I really hope someone can help me figure this out. I know the javascript is not finished and what I currently have is probably wrong but I am just confused on where to take this. Thanks
Function tips() {
var mealCost=parseFloat(document.getElementById("txtMealCost").value);
var Great1= document.getElementById("great");
var Okay2= document.getElementById("okay");
var Poor3= document.getElementById("poor");
var totalCost1= mealCost * .20
if (document.getElementById("great").checked) {
}
}
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr>
How would you rate the service?<br>
Great (20%) <input type="radio" name="radServiceQuality" id="great"> <br>
Okay (15%) <input type="radio" name="radServiceQuality" id="okay"> <br>
Poor (10%) <input type="radio" name="radServiceQuality" id="poor"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="calcTip()">
<div id="output">
</div>
The requirement provided is not clear enough.
Assuming you just need a simple output, what you should do in the function call is,
1.find the value of the selected radio button
document.querySelector('input[name="radServiceQuality"]:checked').value
2a. Decide the tip ratio
if (selected_value = 'great') tip_percentage = 0.2;
2b. Calculate the tip
tip = meal_cost * tip_percentage;
3.output the tip
alert(tip);
You should go through some javascript basic tutorial. And keep on googling.
You can do something like this,
// es6 style function, same as "function(){...}"
tips = () => {
// Getthe selected radio
let selected = document.querySelector(`input[name='radServiceQuality']:checked`);
// If a radio is selected
if (selected) {
// Cast as number
var mealCost = +document.getElementById("txtMealCost").value;
// Format the number as curency
let totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(selected.value * mealCost);
// Set output string
document.getElementById('output').innerText = totalCost;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IT-130 Exam</title>
</head>
<body>
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr> How would you rate the service?
<br> Great (20%) <input type="radio" id='great' name="radServiceQuality" value=".2">
<br> Okay (15%) <input type="radio" id='okay' name="radServiceQuality" value=".15">
<br> Poor (10%) <input type="radio" id='poor' name="radServiceQuality" value=".1"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="tips()">
<div id="output"></div>
</body>
</html>
IFF the HTML is not allowed to be changed, this shall do the trick:
// Helper function to determine percent to apply
getPercent = selectedId => {
switch (selectedId) {
case 'great':
return .2;
case 'okay':
return .15;
case 'poor':
return .1;
}
};
// es6 style function, same as "function(){...}"
calcTip = () => {
// Getthe selected radio
let selected = document.querySelector(`input[name='radServiceQuality']:checked`);
// If a radio is selected
if (selected) {
// set percent
let percent = getPercent(selected.id);
// Cast as number
var mealCost = +document.getElementById("txtMealCost").value;
// Format the number as curency
let totalCost = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(percent * mealCost);
// Set output string
document.getElementById('output').innerText = totalCost;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IT-130 Exam</title>
</head>
<body>
<h1>Tip Calculator</h1>
<hr>
<span>What was the cost of your meal? </span>
<input type="text" id="txtMealCost" />
<hr> How would you rate the service?<br> Great (20%) <input type="radio" name="radServiceQuality" id="great"> <br> Okay (15%) <input type="radio" name="radServiceQuality" id="okay"> <br> Poor (10%) <input type="radio" name="radServiceQuality" id="poor"> <br>
<p><input type="button" value="Calculate Tip Amount" onclick="calcTip()">
<div id="output">
</div>
</body>
</html>
Hope this helps,

Cumulative GPA Calculator

I'm creating a cumulative GPA calculator and I can't get the calculator to output any values. Is there anything I'm doing wrong with the code or calculation?
<div id="Cumulative GPA" class="tabcontent">
<p2>Cumulative GPA <b>before</b> this semester:</p2>
<input type="number" id="oldcumulativegpa">
<br />
<p2><b>Number of semesters</b> your Old Cumulative GPA was calculated with:</p2>
<input type="number" id="numberofsemesters">
<br />
<p2>Your GPA <b>this semester</b>:</p2>
<input type="number" id="currentsemestergpa">
<script>
document.getElementById("oldcumulativegpa").onkeydown = function() {myJsFunction()};
function myJsFunction() {
var oldcumulativegpa = document.getElementById('oldcumulativegpa').value;
var currentsemestergpa = document.getElementById('currentsemestergpa').value;
var numberofsemesters = document.getElementById('numberofsemesters').value;
newcumulativegpa = (oldcumulativegpa*numberofsemesters + currentsemestergpa)/(numberofsemesters + 1);
}
</script>
<p2>Your <b>New Cumulative GPA:</p2>
<p id="newcumulativegpa"></p>
</div>
You have several issues:
The #newcumulativegpa element doesn't exist when you run your <script>
You aren't getting the #newcumulativegpa element, you are creating a global variable newcumulativegpa and assigning to it.
There is no such thing as a <p2> tag
You are only running your function when a key is pressed in the #oldcumulativegpa element
The value property of <input type="number"> is a String. You need to parseFloat(el, 10) to turn it into a Number
Please also see this question, Where should I put tags in HTML markup? about what I mean when I say "#newcumulativegpa element doesn't exist when you run your <script>" doesn't exist when you run your script.
I'm calling that out explicitly because the following runnable script won't demonstrate it well enough.
const oldCumulativeGPAElement = document.getElementById("oldcumulativegpa");
const currentSemesterGPAElement = document.getElementById("currentsemestergpa");
const numberOfSemestersElement = document.getElementById("numberofsemesters");
const newCumulativeGPAElement = document.getElementById('newcumulativegpa');
function updateGPA() {
const oldCumGPA = parseFloat(oldCumulativeGPAElement.value, 10);
const numSemesters = parseFloat(numberOfSemestersElement.value, 10);
const currSemesterGPA = parseFloat(currentSemesterGPAElement.value, 10);
/*
* Test case:
* 4, 3, 3 should show 3.75
*/
const newCumulativeGPA = (
(oldCumGPA * numSemesters) + currSemesterGPA
) / (numSemesters + 1);
newCumulativeGPAElement.innerHTML = newCumulativeGPA;
}
[
oldCumulativeGPAElement,
currentSemesterGPAElement,
numberOfSemestersElement
].forEach(el => el.addEventListener("change", updateGPA));
updateGPA()
<div id="Cumulative GPA" class="tabcontent">
<ul>
<li>
<label>
<span>Cumulative GPA <b>before</b> this semester:</span>
<input type="number" min="0" max="4" step="1" id="oldcumulativegpa" value="4" placeholder="Cumulative GPA">
</label>
</li>
<li>
<label>
<span><b>Number of semesters</b> your Old Cumulative GPA was calculated with:</span>
<input type="number" min="1" step="1" placeholder="Number of semesters" id="numberofsemesters" value="3">
</label>
</li>
<li>
<label>
<span>Your GPA <b>this semester</b>:</span>
<input type="number" min="0" max="4" step="1" value="3" placeholder="GPA this semester" id="currentsemestergpa">
</label>
</li>
</ul>
</div>
<label for="newcumulativegpa">Your New Cumulative GPA:</label>
<output id="newcumulativegpa" for="oldcumulativegpa numberofsemesters currentsemestergpa" name="newcumulativegpa">0</output>
The myJsFunction seemingly calculates the person's GPA given the information provided in the inputs. It makes logical sense, as you take your previous average multiplied over the time you've spent in school, plus your current semester/quarter GPA divided by what will be your total time after this quarter.
The problem, I think, is that you're not actually displaying the result. All you're doing is creating a new tag with the ID of a variable you've declared in your function.

Using Javascript to calculate Form fields with a combination of radio buttons, text fields, and a slider

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script>
function baseCalculate(slider,sqft,plumbing,credit){
var cost = document.getElementById("cost");
var slideval = document.getElementById("slideval");
var sqft = document.getElementById("sqft");
var plumbing = document.getElementsByName("plumbing");
var credit = document.getElementsByName("Credit");
var price = slider;
cost.innerHTML = "$"+(((sqft * price) + plumbing) * credit);
slideval.innerHTML = slider;
}
</script>
</head>
<body>
<h2>Job Estimator</h2>
How many square feet?
<input type="text" id="sqft"><br>
Price per Square Foot? <input type="range" min="55" max="80" value="70" step="1
onChange="baseCalculate(this.value,'sqft','plumbing','Credit')" style="width:500px;">
<span id="slideval">70</span>
<p>
<legend>Will there be plumbing?</legend> <label>
<input type="radio" name="plumbing" value="150" id="plumbing_0">
yes</label>
<br>
<label>
<input type="radio" name="plumbing" value="0" id="plumbing_1">
no</label>
<br>
<label>
<input type="radio" name="plumbing" value="-150" id="plumbing_2">
promo</label>
<br>
</p>
<p><legend>Paying with credit card?</legend>
<label>
<input type="radio" name="Credit" value="1.06" id="Credit_0">
Yes</label>
<br>
<label>
<input type="radio" name="Credit" value="1" id="Credit_1">
No</label>
<br>
<label>
<input type="radio" name="Credit" value=".94" id="Credit_2">
Promo</label>
<br>
</p>
<h2>This is the cost of the project: <span id="cost"></span></h2>
</body>
</html>
This is the code I am using. I am trying to get it to multiply the sqft times the price then add on the plumbing and then multiply all that by the credit.
What am I missing here? It returns a NaN.
Thanks for any help provided.
You have to get the text value using textContent and perform a calculation
var cost = document.getElementById("cost").textContent;
var slideval = document.getElementById("slideval").textContent;
var sqft = document.getElementById("sqft").textContent;
and also value for input element
var plumbing = document.getElementsByName("plumbing")[0].value;
var credit = document.getElementsByName("Credit")[0].value;
getElementsByName will return the array and here i took the first value [0]
Your case you need to do a for loop and check for checked attribute and get its value for calculation

Categories

Resources