javascript help using html and calculator - javascript

Can someone help me to get the total price of the stock given prices below?? Using the onclick, once someone puts in the number of stocks they want to buy, how do I go about getting the total price of all 3 stocks choosen??
<tr>
<td><b> SHARE PRICE</b></td>
<td>$43.93</td>
<td>$43.87</td>
<td>$26.33</td>
</tr>
</table>
<hr>
<br>
<p>
<h3>Important information that you should know about these stocks: </h3>
<ul>
<li>0.1% of the trade value if the total trade value is less than $10,000</li>
<li>0.08% of the trade value if the total trade value is greater than or equal to $10,000</li>
<li>The minimum commission is $5</li>
<hr>
<br>
</ul>
<form name="calculator">
<p> Enter the number of Oracle Corporation stocks you wish to purchase!: <input type="text" id="input1"></p> <br>
<p> Enter the number of Microsoft Corporation stocks you wish to purchase!: <input type="text" id="input2"></p> <br>
<p> Enter the number of Symantec Corporation stocks you wish to purchase!: <input type="text" id="input3"></p> <br

I would suggest storing the price information as a numeric value somewhere, like in hidden input fields or data- attributes on the table cells, and create IDs on those elements that you can associate with the inputs for stock purchases. Then it's just a matter of doing some simple math. Here's an example using hidden inputs:
<table>
<tr>
<td><b> SHARE PRICE</b></td>
<td>$43.93</td>
<td>$43.87</td>
<td>$26.33</td>
</tr>
</table>
<h3>Important information that you should know about these stocks: </h3>
<ul>
<li>0.1% of the trade value if the total trade value is less than $10,000</li>
<li>0.08% of the trade value if the total trade value is greater than or equal to $10,000</li>
<li>The minimum commission is $5</li>
</ul>
<form name="calculator">
<input type="hidden" id="price1" value="43.93" />
<input type="hidden" id="price2" value="43.87" />
<input type="hidden" id="price3" value="26.33" />
<p> Enter the number of Oracle Corporation stocks you wish to purchase!: <input type="text" id="input1"></p> <br>
<p> Enter the number of Microsoft Corporation stocks you wish to purchase!: <input type="text" id="input2"></p> <br>
<p> Enter the number of Symantec Corporation stocks you wish to purchase!: <input type="text" id="input3"></p> <br>
<input type="button" value="Add!" onclick="javascript:sumUp()" />
</form>
<script type="text/javascript">
function sumUp() {
var total = (document.getElementById("price1").value * document.getElementById("input1").value) + (document.getElementById("price2").value * document.getElementById("input2").value) + (document.getElementById("price3").value * document.getElementById("input3").value)
alert("Your total is: $" + total);
}
</script>
Here's the code for putting the total into a textbox. This would go at the end of your form and replace the <script> block from the first example.
<p>Your total is: $<input type="text" id="total" /></p>
<script type="text/javascript">
function sumUp() {
var total = (document.getElementById("price1").value * document.getElementById("input1").value) + (document.getElementById("price2").value * document.getElementById("input2").value) + (document.getElementById("price3").value * document.getElementById("input3").value)
document.getElementById("total").value = total;
}
</script>

Related

Multiple calculations and targeted output in 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>

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

Using For Loop in Javascript?

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.

how to add a basic input discount on javascript

This is the code i want to create this form were you input all the information like price, quantity and %discount and have the discount amount shown the subtotal and the total
as the discount amount being the %discount divided by 100 and then multiplied by the subtotal. The subtotal is made by multiplying the price by quantity. And the total is made by multiplying the subtotal by discount as you can see i have the form complete and i have almost all the code on the javascript but it seems i cant make it work with the discount. Please help !
JS:
$('#CAT_Custom_490527').keyup(function () {
var quantity = $("#CAT_Custom_490527").val();
var iPrice = $("#CAT_Custom_490526").val();
var subtotal = quantity * iPrice;
$("#CAT_Custom_491101").val(subtotal);
var x = $("#CAT_Custom_491074").val();
var y = 100
var division = x / y
var multi = division * subtotal
$("CAT_Custom_491074").val(division);
var total = subtotal * multi;
$("#CAT_Custom_490531").val(total);
// sets the total price input to the quantity * price
});
HTML:
<tr>
<td>
<label for="CAT_Custom_490526">Precio <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490526" id="CAT_Custom_490526" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_490527">Cantidad <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490527" id="CAT_Custom_490527" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491074">%Descuento</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491074" id="CAT_Custom_491074" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491218">Descuento</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491218" id="CAT_Custom_491218" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_491101">Subtotal</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_491101" id="CAT_Custom_491101" class="cat_textbox" />
</td>
</tr>
<tr>
<td>
<label for="CAT_Custom_490531">Total <span class="req">*</span>
</label>
<br />
<input type="text" maxlength="255" name="CAT_Custom_490531" id="CAT_Custom_490531" class="cat_textbox" />
</td>
</tr>
Trouble spots I see:
Incorrect Math (thanks to answer by krb686 - please upvote that answer since it is helpful)
Typo in selector - missing # (thanks to answer by Kundan Singh Chouhan - please upvote that answer since it is helpful)
After correcting the typo above, you are now overwriting the discount percent. I bet you meant that to be used for the discount value field: #CAT_Custom_491218. This would be much easier to detect ahead of time if you use meaningful ids instead of auto-generated ids.
You are only evaluating this function when the quantity field is changed. If you change, for example, the discount percent, the subtotal and total are not re-evaluated.
You are only watching keyboard events. If the value was changed using the mouse only (copy/paste or drag/drop), the subtotal and total are not re-evaluated. Also handle oninput (a new event for html5) and onchange.
To bind to all of the inputs and detect more events than just keyup:
$("input").on("input keyup change", function () {
...
Demo with all the above changes applied
You missed the "#" form your textbox ID, it should be
$("#CAT_Custom_491074").val(division);
This will fix your issue.
Your math is incorrect
So if I enter 50 in the discount box, x = 50, y = 100,
division = x/y = 50/100 = 0.5
Say subtotal = $100, then multi = subtotal * division = $100 * 0.5 = $50
Then, total = subtotal * multi = $100 * $50 = $5000
You shouldn't be multiplying subtotal * multi.
Why don't you just do:
total = subtotal * (1 - discount/100)
Essentially (1 - discount/100) is your multiplier. If I enter 12 for discount, it becomes:
total = ($100) * (1 - 12/100), or ($100) * 0.88, or $88
Or
Just change your last line of code to:
total = subtotal - multi
multi isn't holding a multiplier, it's holding the amount you want to take off the total.

calculating the sum of the array form with javascript

I want to display the number of values ​​in array form. I have a lot of form with only one name is "price []" and have each value on the form. I want to calculate the total value of the form "price []". I'm still a beginner in javascript. and I want to calculate it by using javascript. The following coding that I have made.
<html>
<body>
<form id="hitung" name="hitung">
price 1 <input type="text" name="price[]" class="price" value="1000"/><br>
price 2 <input type="text" name="price[]" class="price" value="3000"/><br>
price 3 <input type="text" name="price[]" class="price" value="2000"/><br>
price 4 <input type="text" name="price[]" class="price" value="1000"/><br>
price 5 <input type="text" name="price[]" class="price" value="3000"/><br><br>
total <input type="text" name="total" class="total"/>
</form>
</body>
</html>
and I want to ask you again, if there is a new input from the outside, then the total will also be changed directly. how to do it. help me please. thank you
Here's an example: http://jsfiddle.net/c4UyA/1/
var sum = 0;
$("form > input[name='price[]']").each(function() {
$this = $(this);
sum += parseInt($this.attr("value"));
});
$("form > input[name='total']").attr("value", sum);

Categories

Resources