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
Related
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>
Also my I need help with the loop to add more names when I put the number 2 instead of 1. Having issues with my code any help is appreciated. I know its simple For Loop coding, but I am stumped.
HTML
<p>Enter First Name: <input type="text" id="firstname">
<span id="firstname_error"></span>
</p>
<p>Enter Last Name: <input type="text" id="lastname">
<span id="lastname_error"></span>
</p>
<p>How Many Pets do you have? (0-3):
<input type="text" id="numpets" size="1" maxlength="1">
<span id="numpets_error"></span>
</p>
<p>List your Pet's names:
<input type="text" id="pet1">
<input type="text" id="pet2">
<input type="text" id="pet3">
</p>
<p><input id="mybutton" type="button" value="Submit Information"></p>
<p id="message"></p>
JavaScript
for(counter=1; counter<=numpets; counter++) {
var PetId = "pet" + counter;
var myPetName = document.getElementById(PetId).value;
// Code to append test into a message variable
}
I have a total of three fields in the var "numpets", if I put the number 1 in that field, it will only the read the name in the number 1 field. If I put 2 it will only read the name in the number 2 field. I need it to be able to read all 3 three fields.
The for loop is ok. You have just to put your loop inside a function and call it with your button. And define the numpets like you did with the var namepet.
I want to user to press submit button so that their name and age is displayed in the input box with name="output"?
I have 3 input boxes, one asking for name and the other for age while the other one provides output. I am trying to use the function output() to display the last input box.
I am confused about where I am going wrong, do I need a .value?
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = getElementByName('firstName');
var Age= getElementByName('age');
var out = document.write(name+Age);
document.getElementByName('output') = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" name="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" name="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output"></input>
</center>
</div>
</body>
</html>
Here's a working version of your code.
There's no method getElementByName (but getElementsByName) - you should use document.getElementById() (Read about it here)
You should use the value of the input element.
<!doctype html>
<html>
<head>
<style>
.formdiv{
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output(){
var name = document.getElementById('firstName').value;
var Age= document.getElementById('age').value;
document.getElementById('output').value = name+Age;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset><center>
<legend> Enter the following Info:</legend>
<br />
<label> Name </label>
<input type="text" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age </label>
<input type="number" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button><br/>
<label for="output">Output</label>
<br/>
<input type="textbox" id="output"></input>
</center>
</div>
</body>
</html>
getElementsByName (note: Elements, not Element) returns a list of Elements, in this case your <input>s. So first of all, you need to select the first (in your case your only one) using getElementsByName(...)[0]. Then you get one Element.
However you do not want to output the entire element (which is an Object, not a String, and converted to a string it likely won't be what you expect), so you need to select the value property of that Element. So yes, you need to add .value, just as you assumed:
function output(){
var name = getElementsByName('firstName')[0].value;
var Age= getElementsByName('age')[0].value;
Then, document.write writes the argument to a new document directly, which results in an emtpy page with nothing else on it but that string. This isn't what you want, so you don't need that. ALl you do want is to assign a new variable called out with that string:
var out = name+Age;
Then to assigning the new value to the output field - you don't want to replace the Element by a string (that wouldn't even work), but it's value, so you need the .value again:
document.getElementsByName('output')[0].value = out;
}
That should do the trick.
(In addition to that, you might want to use name + " " + Age instead of simply name+Age, as otherwise you end up with "John Doe23" instead of "John Doe 23" which you likely want)
There are a few things wrong with your code:
there is no such thing as getElementByName - it is getElementById
changing to the above, you need to add ids to your input elements
you need to use the value of the returned object from getElementById
The above will get your code working, but also, the center tag is obsolete and you shouldn't use it
Inputs are self closing tags so you don't need </input>
<!doctype html>
<html>
<head>
<style>
.formdiv {
align: center;
}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
function output() {
var name = document.getElementById('firstName').value;
var Age = document.getElementById('age').value;
var out = name + Age;
document.getElementById('output').value = out;
}
</script>
<h1><strong><em><center>Payment Details</center></em></strong> </h1>
<div class="formdiv">
<fieldset>
<center>
<legend>Enter the following Info:</legend>
<br />
<label>Name</label>
<input type="text" name="firstName" id="firstName" placeholder="John" required="required"></input>
<br/>
<br/>
<label>Age</label>
<input type="number" name="age" id="age" maxlength="2" required="required"></input>
</fieldset>
</center>
</div>
<div>
<center>
<button onClick="output()">Submit</button>
<br/>
<label for="output">Output</label>
<br/>
<input type="textbox" name="output" id="output"></input>
</center>
</div>
</body>
</html>
I have a logic error and cant seem to find it. I think I am "getting" the elements by ID correctly, but it yields NAN. Any help with this is appreciated.
I am not sure what else I am doing wrong, any suggestions are welcome. I am new to DOM and not very familiar with Javascript.
var avgGrade
function calcAvg()
{
avgGrade = document.getElementById("finalExam") +
document.getElementById("homework") + document.getElementById("projects");
alert("Your average is " + avgGrade);
document.getElementById("stuAverage").value = avgGrade;
}
//-->
</script>
</head>
<body>
<h1>Calculate average</h1>
<h3>Enter the following information and then press the <b>AVERAGE</b> button
to calculate
your grade.</h3>
<p>To clear the data fields, click here <b>Refresh this page</b></p>
<form action="#" name="gradeInfo" id="gradeInfo">
<p>
Enter Final Exam Grade:
<input type="text" name="finalExam" id="finalExam" size="4" /><br />
Enter Homework Grade:
<input type="text" name="homework" id="homework" size="4" /><br />
Enter Projects Grade:
<input type="text" name="projects" id="projects" size="4" /><br />
<br /><br />
<input type="button" value="AVERAGE" onclick="calcAvg()" />
<br /><br />
Your Average is:
<input type="text" name="stuAverage" id="stuAverage" size="4" /><br />
</p>
</form>
</body>
</html>
First missing a ; at the end of var avgGrade
Second you need to get values of the inputs not the inputs itself.
document.getElementById("homework").value
Third you need to convert the values from string to integer using parseInt
avgGrade = parseInt(document.getElementById("finalExam").value) +
parseInt(document.getElementById("homework").value) +
parseInt(document.getElementById("projects").value);
jsfiddle DEMO
P.s. you gotta divide it to the number of grades to get the average.
to get the value in the input field you need to write -
document.getElementById("finalExam").value
To learn and study JavaScript, im trying to do a calculator, and as start i tried to do a sum operation by taking 2 input. But somehow there is a problem that i cant see. Can you help me?
Here is the code:
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" name="n1" /><br>
Number 2: <input type="text" name="n2" /><br>
</form>
<button id="b" onclick="func();" />Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum() {
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>
Replace:
function sum() {
With:
function func() {
This prevents you from assigning 2 different types / values to the same variable name.
(You've got an sum function and a sum variable in your question.)
Replace:
document.write(sum);
With
document.getElementById('b').innerHTML = sum;
This snippet adds the result of sum to <p id="b"></p> (So, the result may be: <p id="b">18</p>, for example), instead of arbitrarily adding it to the end of your HTML.
And finally, replace:
Number 1: <input type="text" name="n1"/><br>
Number 2: <input type="text" name="n2"/><br>
With:
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
document.getElementById looks for the id attribute in your HTML, not for the name.
There are two problems:-
Change onclick="func();" to onclick="sum();" , you are calling the wrong/undefined function.
<button id="b" onclick="sum();"/>Sum</button>
Assign input tags id as n1 and n2, you have assigned them as name and are referring to them based on id getElementById()
Number 1: <input type="text" id="n1"/><br>
Number 2: <input type="text" id="n2"/><br>
<html>
<body>
<h1> JavaScript Test </h1>
Sum The Nums Up!
<br>
<form>
Number 1: <input type="text" id="n1" name="n1"/><br>
Number 2: <input type="text" id="n2" name="n2"/><br>
</form>
<button id="b" onclick="sum();"/>Sum</button>
<p id="b"></p>
<script type="text/javascript">
function sum()
{
var nn1 = document.getElementById("n1").value;
var nn2 = document.getElementById("n2").value;
var sum = parseInt(nn1) + parseInt(nn2);
document.write(sum);
}
</script>
</body>
</html>