I created (build on template) a simple js form. Everything is working with "radio" and "select" input, but i cant connect a "range" value for sum it with everything else.
this how form and calculations works: (sorry for a lot of noobcode)
function showVal(newVal){
document.getElementById("valBox").innerHTML=newVal;
}
function valNum(){
var valNum = document.getElementById("valBox")
}
var cake_prices = new Array();
cake_prices["Round6"]=9;
cake_prices["Round8"]=11;
cake_prices["Round10"]=12;
var filling_prices= new Array();
filling_prices["Yearone"]=12;
filling_prices["Yeartwo"]=60;
filling_prices["Yearthree"]=120;
var billing_prices= new Array();
billing_prices["Billone"]=100;
billing_prices["Billtwo"]=200;
billing_prices["Billthree"]=300;
billing_prices["Billfour"]=400;
billing_prices["Billfive"]=300;
function getCakeSizePrice()
{
var cakeSizePrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the cake the user Chooses name=selectedCake":
var selectedCake = theForm.elements["selectedcake"];
//Here since there are 4 radio buttons selectedCake.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCake.length; i++)
{
//if the radio button is checked
if(selectedCake[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
cakeSizePrice = cake_prices[selectedCake[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return cakeSizePrice;
}
function getBillingPrice()
{
var cakeBillingPrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the select id="filling"
var selectedBilling = theForm.elements["billing"];
//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
cakeBillingPrice = billing_prices[selectedBilling.value];
//finally we return cakeFillingPrice
return cakeBillingPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cakePrice = (getCakeSizePrice() + getBillingPrice()) * valNum();
var num = (cakePrice);
var miPrice = parseInt (num - (num * .35));
var miDiff = parseInt(cakePrice - miPrice);
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total "+cakePrice;
var divobj = document.getElementById('miPrice');
divobj.style.display='block';
divobj.innerHTML = "Total "+miPrice;
var divobj = document.getElementById('miDiff');
divobj.style.display='block';
divobj.innerHTML = "Total "+miDiff;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Cake Form</title>
<script type="text/javascript" src="js/formcalculations.js"></script>
<link href="styles/cakeform.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrap">
<form action="" id="cakeform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<label >Select your province</label>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round6" onclick="calculateTotal()" />SASKATCHEWAN</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round8" onclick="calculateTotal()" />MANITOBA</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round10" onclick="calculateTotal()" />ALBERTA</label><br/>
<br/>
<br/>
<br>
</br>
<label >BILL</label>
<select id="billing" name='billing' onchange="calculateTotal()">
<option value="Billone">100</option>
<option value="Billtwo">200</option>
<option value="Billthree">300</option>
<option value="Billfour">400</option>
<option value="Billfive">500</option>
</select>
<br/>
<label >TOTAL WITH UTILITY</label>
<div id="totalPrice"></div>
<label >TOTAL WITH MI</label>
<div id="miPrice"></div>
<label >TOTAL SAVED</label>
<div id="miDiff"></div>
<br>
<span id="valBox"></span>
<input type="range" min="5" max="10" step="1"
oninput="showVal(this.value)" onchange="showVal(this.value)">
</fieldset>
</div>
</div>
</form>
</div><!--End of wrap-->
</body>
</html>
everything is working without "range" input and valNum (do i created it correctly?) function.
like if I'm doing:
function calculateTotal()
{
var cakePrice = (getCakeSizePrice() + getBillingPrice());
}
but when I'm adding newVal function chrome showing me total: NaN;
function calculateTotal()
{
var cakePrice = (getCakeSizePrice() + getBillingPrice()+newVal();
}
everything is working without "range" input and valNum (do i created it correctly?) function....
var cakePrice = (getCakeSizePrice() + getBillingPrice()) * valNum();
-valNum() func does not return any value.
but when I'm adding newVal function chrome showing me total: NaN;
var cakePrice = (getCakeSizePrice() + getBillingPrice()+newVal();
-I don't see a newVal() func in the code. There is a newVal variable, but its scope is limited to the fucntion.
Define a global variable and then define the function as below:
var valNum;
function valNum(){
valNum = document.getElementById("valBox")
}
And make use of valNum as below :
var cakePrice = (parseFloat(getCakeSizePrice()) + parseFloat(getBillingPrice())) * parseFloat(valNum);
Related
Hi I'm trying to make a webpage to calculate cake prices using this example: http://javascript-coder.com/javascript-form/javascript-calculator-script.phtml
All the code is also available here.
I want to make the filling price more expensive if their cake is bigger, how can I change this?
So if a user selects a bigger cake I want to increase the price of the filling. Not just with a certain % but with a different amount of $ depending on the size and filling, I would prefer to change the "filling_prices" array depending on the size of the cake.
I tried this:
if (cake_prices[selectedCake[i].value] == 20){
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=5;
filling_prices["Custard"]=5;
filling_prices["Fudge"]=7;
filling_prices["Mocha"]=8;
filling_prices["Raspberry"]=10;
filling_prices["Pineapple"]=5;
filling_prices["Dobash"]=9;
filling_prices["Mint"]=5;
filling_prices["Cherry"]=5;
filling_prices["Apricot"]=8;
filling_prices["Buttercream"]=7;
filling_prices["Chocolate Mousse"]=12;
}
else{
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=10;
filling_prices["Custard"]=10;
filling_prices["Fudge"]=14;
filling_prices["Mocha"]=16;
filling_prices["Raspberry"]=20;
filling_prices["Pineapple"]=10;
filling_prices["Dobash"]=18;
filling_prices["Mint"]=10;
filling_prices["Cherry"]=10;
filling_prices["Apricot"]=16;
filling_prices["Buttercream"]=14;
filling_prices["Chocolate Mousse"]=24;
}
This doesn't seem to work, how could I make this work? I'm sorry if this is kind of a stupid question but I'm just starting out.
HTML code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Cake Form</title>
<script type="text/javascript" src="js/formcalculations.js"></script>
<link href="styles/cakeform.css" rel="stylesheet" type="text/css" />
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="cakeform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Make your cake!</legend>
<label >Size Of the Cake</label>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round6" onclick="calculateTotal()" />Round cake 6" - serves 8 people ($20)</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round8" onclick="calculateTotal()" />Round cake 8" - serves 12 people ($25)</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round10" onclick="calculateTotal()" />Round cake 10" - serves 16 people($35)</label><br/>
<label class='radiolabel'><input type="radio" name="selectedcake" value="Round12" onclick="calculateTotal()" />Round cake 12" - serves 30 people($75)</label><br/>
<br/>
<label >Filling</label>
<select id="filling" name='filling' onchange="calculateTotal()">
<option value="None">Select Filling</option>
<option value="Lemon">Lemon($5)</option>
<option value="Custard">Custard($5)</option>
<option value="Fudge">Fudge($7)</option>
<option value="Mocha">Mocha($8)</option>
<option value="Raspberry">Raspberry($10)</option>
<option value="Pineapple">Pineapple($5)</option>
<option value="Dobash">Dobash($9)</option>
<option value="Mint">Mint($5)</option>
<option value="Cherry">Cherry($5)</option>
<option value="Apricot">Apricot($8)</option>
<option value="Buttercream">Buttercream($7)</option>
<option value="Chocolate Mousse">Chocolate Mousse($12)</option>
</select>
<br/>
<p>
<label for='includecandles' class="inlinelabel">Include Candles($5)</label>
<input type="checkbox" id="includecandles" name='includecandles' onclick="calculateTotal()" />
</p>
<p>
<label class="inlinelabel" for='includeinscription'>Include Inscription($20)</label>
<input type="checkbox" id="includeinscription" name="includeinscription" onclick="calculateTotal()" />
<input type="text" id="theinscription" name="theinscription" value="Enter Inscription" />
</p>
<div id="totalPrice"></div>
</fieldset>
</div>
<div class="cont_details">
<fieldset>
<legend>Contact Details</legend>
<label for='name'>Name</label>
<input type="text" id="name" name='name' />
<br/>
<label for='address'>Address</label>
<input type="text" id="address" name='address' />
<br/>
<label for='phonenumber'>Phone Number</label>
<input type="text" id="phonenumber" name='phonenumber'/>
<br/>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="calculateTotal()" />
</div>
</form>
</div><!--End of wrap-->
</body>
</html>
I changed
if (cake_prices[selectedCake[i].value] == 20){
to
if (getCakeSizePrice() == 20){
in the javascript code, but it doesn't seem to work
Javascript code:
/*
This source is shared under the terms of LGPL 3
www.gnu.org/licenses/lgpl.html
You are free to use the code in Commercial or non-commercial projects
*/
//Set up an associative array
//The keys represent the size of the cake
//The values represent the cost of the cake i.e A 10" cake cost's $35
var cake_prices = new Array();
cake_prices["Round6"]=20;
cake_prices["Round8"]=25;
cake_prices["Round10"]=35;
cake_prices["Round12"]=75;
//Set up an associative array
//The keys represent the filling type
//The value represents the cost of the filling i.e. Lemon filling is $5,Dobash filling is $9
//We use this this array when the user selects a filling from the form
// getCakeSizePrice() finds the price based on the size of the cake.
// Here, we need to take user's the selection from radio button selection
function getCakeSizePrice()
{
var cakeSizePrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the cake the user Chooses name=selectedCake":
var selectedCake = theForm.elements["selectedcake"];
//Here since there are 4 radio buttons selectedCake.length = 4
//We loop through each radio buttons
for(var i = 0; i < selectedCake.length; i++)
{
//if the radio button is checked
if(selectedCake[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
cakeSizePrice = cake_prices[selectedCake[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return cakeSizePrice;
}
// var filling_prices= new Array();
// filling_prices["None"]=0;
// filling_prices["Lemon"]=5;
// filling_prices["Custard"]=5;
// filling_prices["Fudge"]=7;
// filling_prices["Mocha"]=8;
// filling_prices["Raspberry"]=10;
// filling_prices["Pineapple"]=5;
// filling_prices["Dobash"]=9;
// filling_prices["Mint"]=5;
// filling_prices["Cherry"]=5;
// filling_prices["Apricot"]=8;
// filling_prices["Buttercream"]=7;
// filling_prices["Chocolate Mousse"]=12;
if (getCakeSizePrice() == 20){
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=5;
filling_prices["Custard"]=5;
filling_prices["Fudge"]=7;
filling_prices["Mocha"]=8;
filling_prices["Raspberry"]=10;
filling_prices["Pineapple"]=5;
filling_prices["Dobash"]=9;
filling_prices["Mint"]=5;
filling_prices["Cherry"]=5;
filling_prices["Apricot"]=8;
filling_prices["Buttercream"]=7;
filling_prices["Chocolate Mousse"]=12;
}
else{
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=10;
filling_prices["Custard"]=10;
filling_prices["Fudge"]=14;
filling_prices["Mocha"]=16;
filling_prices["Raspberry"]=20;
filling_prices["Pineapple"]=10;
filling_prices["Dobash"]=18;
filling_prices["Mint"]=10;
filling_prices["Cherry"]=10;
filling_prices["Apricot"]=16;
filling_prices["Buttercream"]=14;
filling_prices["Chocolate Mousse"]=24;
}
//This function finds the filling price based on the
//drop down selection
function getFillingPrice()
{
var cakeFillingPrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the select id="filling"
var selectedFilling = theForm.elements["filling"];
//set cakeFilling Price equal to value user chose
//For example filling_prices["Lemon".value] would be equal to 5
cakeFillingPrice = filling_prices[selectedFilling.value];
//finally we return cakeFillingPrice
return cakeFillingPrice;
}
//candlesPrice() finds the candles price based on a check box selection
function candlesPrice()
{
var candlePrice=0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the checkbox id="includecandles"
var includeCandles = theForm.elements["includecandles"];
//If they checked the box set candlePrice to 5
if(includeCandles.checked==true)
{
candlePrice=5;
}
//finally we return the candlePrice
return candlePrice;
}
function insciptionPrice()
{
//This local variable will be used to decide whether or not to charge for the inscription
//If the user checked the box this value will be 20
//otherwise it will remain at 0
var inscriptionPrice=0;
//Get a refernce to the form id="cakeform"
var theForm = document.forms["cakeform"];
//Get a reference to the checkbox id="includeinscription"
var includeInscription = theForm.elements["includeinscription"];
//If they checked the box set inscriptionPrice to 20
if(includeInscription.checked==true){
inscriptionPrice=20;
}
//finally we return the inscriptionPrice
return inscriptionPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cakePrice = getCakeSizePrice() + getFillingPrice() + candlesPrice() + insciptionPrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Cake $"+cakePrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
You have to set filling_prices when you change cake size. What happens now is that getCakeSizePrice() returns 0 at the start of your program. So the filling_prices will be set to the cheaper prices and will never change.
Here is a working codepen: https://codepen.io/martitv/pen/WYYdNq?editors=0010
Due to how you program is structured, this should be done in calculateTotal()
Create a function like this:
var filling_prices;
function setFillingPrices(cakeSizePrice) {
if (cakeSizePrice == 20){
filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=5;
filling_prices["Custard"]=5;
filling_prices["Fudge"]=7;
filling_prices["Mocha"]=8;
filling_prices["Raspberry"]=10;
filling_prices["Pineapple"]=5;
filling_prices["Dobash"]=9;
filling_prices["Mint"]=5;
filling_prices["Cherry"]=5;
filling_prices["Apricot"]=8;
filling_prices["Buttercream"]=7;
filling_prices["Chocolate Mousse"]=12;
}
else{
filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=10;
filling_prices["Custard"]=10;
filling_prices["Fudge"]=14;
filling_prices["Mocha"]=16;
filling_prices["Raspberry"]=20;
filling_prices["Pineapple"]=10;
filling_prices["Dobash"]=18;
filling_prices["Mint"]=10;
filling_prices["Cherry"]=10;
filling_prices["Apricot"]=16;
filling_prices["Buttercream"]=14;
filling_prices["Chocolate Mousse"]=24;
}
setFillingPriceText();
}
then call it in your calculateTotal() like this:
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cakeSizePrice = getCakeSizePrice();
var fillingPrice = getFillingPrice(cakeSizePrice);
var candlesPrice = getCandlesPrice();
var insciptionPrice = getInsciptionPrice();
var cakePrice = cakeSizePrice + fillingPrice + candlesPrice + insciptionPrice;
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Cake $"+cakePrice;
}
I also created a function called setFillingPriceText() that updates the options labels/text with the new price when selecting a new cakesize.
It looks like this:
function setFillingPriceText() {
var theForm = document.forms["cakeform"];
//Get a reference to the select id="filling"
var fillingElements = theForm.elements["filling"].options;
var fillings = Object.keys(filling_prices);
for(var i = 1; i < fillingElements.length; i++){
fillingElements[i].text = fillings[i] + "(" + filling_prices[fillings[i]] + "$)";
}
}
I'm having issues with a simple price calculator I'm making. I've learned Javascript and I went over everything and it looks fine, but I'm definitely missing something since the final price isn't appearing. I've checked it a few times but maybe it needs a new set of eyes:
<form action="" name="costcalculator" id="costcalculator" onsubmit="return false;"> // I put name and ID to be safe
<b>1.</b> What type of website do you need?<br>
<input type="radio" name="typesite" value="Standard" onclick="calculateTotal()" />
A standard website<br>
<input type="radio" name="typesite" value="Full Blog" onclick="calculateTotal()" />
A website that allows visitors to leave comments on blog posts<br>
<center><input type='submit' id='submit' value='Submit' onclick="calculateTotal()" /></center><p>
<div id="totalPrice"></div> </form>
The script:
var typesite = new Array(); // typesite is taken from the HTML
typesite["Standard"]=20;
typesite["Full Blog"]=30;
function getLayoutPrice() // new name for function
{
var layoutPrice=0; // new name for the variable
var theForm = document.forms["costcalculator"]; // comes from form name/ID
var typeSite = theForm.elements["typesite"]; // new variable name and name from HTML
for(var i = 0; i < typeSite.length; i++)
{
if(typeSite[i].checked)
{
layoutPrice = typesite[typeSite[i].value];
break;
}
}
return layoutPrice; // taken from the variable created earlier
}
function calculateTotal()
{
var totalPrice = getLayoutPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price would be about $"+totalPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
Tested in current Chrome and Firefox and seems to work fine, as can be observed from running the snippet below.
var typesite = new Array(); // typesite is taken from the HTML
typesite["Standard"]=20;
typesite["Full Blog"]=30;
function getLayoutPrice() // new name for function
{
var layoutPrice=0; // new name for the variable
var theForm = document.forms["costcalculator"]; // comes from form name/ID
var typeSite = theForm.elements["typesite"]; // new variable name and name from HTML
for(var i = 0; i < typeSite.length; i++)
{
if(typeSite[i].checked)
{
layoutPrice = typesite[typeSite[i].value];
break;
}
}
return layoutPrice; // taken from the variable created earlier
}
function calculateTotal()
{
var totalPrice = getLayoutPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price would be about $"+totalPrice;
}
function hideTotal()
{
var divobj = document.getElementById('totalPrice');
divobj.style.display='none';
}
<form action="" name="costcalculator" id="costcalculator" onsubmit="return false;"> // I put name and ID to be safe
<b>1.</b> What type of website do you need?<br>
<input type="radio" name="typesite" value="Standard" onclick="calculateTotal()" />
A standard website<br>
<input type="radio" name="typesite" value="Full Blog" onclick="calculateTotal()" />
A website that allows visitors to leave comments on blog posts<br>
<center><input type='submit' id='submit' value='Submit' onclick="calculateTotal()" /></center><p>
<div id="totalPrice"></div> </form>
I have a calculator. This has a form which, for certain calculations, works only when I refresh the page. Addition works but multiplication only works after refresh. Why is that?
I don't want to use JQuery!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Card Form</title>
<link href="styles/cardform.css" rel="stylesheet" type="text/css" />
</head>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="cardform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Check Quotes</legend>
<label>Size Of the Card</label>
<label>Width in cm: </label> <input type="text" id="width" />
<label>Height in cm: </label> <input type="text" id="height" />
<br/>
<br/>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round13" onclick=""/>Standard</label>
<label class='radiolabel'><input type="radio" name="selectedcard1" value="Round14" onclick="" />Toughened</label><br/>
<br/>
<label>Card: </label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round17" onclick=""/>Clear</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round18" onclick="" />Frosted</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round19" onclick="" />Leaded</label>
<label class='radiolabel'><input type="radio" name="selectedcard2" value="Round20" onclick="" />White Bar</label>
<br/>
<label>Frame: </label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round21" onclick=""/>uPVC</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round22" onclick="" />Metal</label>
<label class='radiolabel'><input type="radio" name="selectedcard3" value="Round23" onclick=""/>Wood</label>
<br/>
<input type="submit" value="Calculate" onClick="calculateTotal()" />
<INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()" />
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
<script>
var size1 = document.getElementById("width").value;
var size2 = document.getElementById("height").value;
var total_size = ((size1 * size2) / 10000);
var card_prices = new Array();
card_prices["Round13"] = (total_size * 67);
card_prices["Round14"] = (total_size * 87);
card_prices["Round17"] = (total_size * 0.05);
card_prices["Round18"] = (total_size * 0.65);
card_prices["Round19"] = (total_size * 0.85);
card_prices["Round20"] = (total_size * 0.95);
function getCardSizePrice2() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard1 = theForm.elements["selectedcard1"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard1.length; i++) {
//if the radio button is checked
if (selectedCard1[i].checked) {
//we set cardSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" card we set it to 25
//by using the card_prices array
//We get the selected Items value
//For example card_prices["Round8".value]"
cardSizePrice = card_prices[selectedCard1[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cardSizePrice
return cardSizePrice;
}
function getCardSizePrice3() {
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard2"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
function getCardSizePrice4() {
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
var cardSizePrice = 0;
//Get a reference to the form id="cardform"
var theForm = document.forms["cardform"];
//Get a reference to the card the user Chooses name=selectedCard":
var selectedCard = theForm.elements["selectedcard3"];
//Here since there are 4 radio buttons selectedCard.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCard.length; i++) {
//if the radio button is checked
if (selectedCard[i].checked) {
cardSizePrice = card_prices[selectedCard[i].value];
break;
}
}
return cardSizePrice;
}
var divobj = document.getElementById('totalPrice');
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice2() + getCardSizePrice3() + getCardSizePrice4();
//display the result
divobj.style.display = 'block';
divobj.innerHTML = "Total Price For the Card: £" + " " + cardPrice;
displaytotal(divobj);
}
function displaytotal() {
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
function resetIt() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
</script>
</html>
I understand you've found your issue (I believe it had to do with the fact that you had your code set up with a submit button and you had totals being calculated as soon as the page load event triggered, rather than upon a click of the total button).
But, beyond that, you may still want to look at this answer very carefully as the code you have is just awful in many regards:
HTML:
Your HTML was not being used correctly. You were not using <label>
or <fieldset> elements properly.
Since you were really just needing a calculator that doesn't actually
submit the data anywhere, you shouldn't have a submit button.
You were using inline HTML event handlers (onsubmit, onclick,
etc.), which should not be used because:
They create "spaghetti code" that is difficult to read and leads to
duplication of code.
They cause global event handling wrapper functions to be implicitly
created around the attribute values that you supply that make the
binding of the this object not work as expected.
They don't follow W3C Standards for Event Handling
JavaScript:
You were setting up variables for the HTML elements you were going to
use inside your various functions, which meant that every time the
function runs, it has to re-scan the document all over again to find
the element.
You were using an array when an Object was more appropriate.
You had essentially the same function written 3 times instead of just
having it once and passing an argument to it that can change as you
need it to.
Here is a cleaned up version that follows best-practices, semantics and doesn't repeat itself. See the inline comments for specifics.
window.addEventListener("DOMContentLoaded", function(){
// Get references to DOM elements that we'll need access to just once. Don't set variables
// up to store their values at first. Set the variable to the elmement. That way, you can
// go back to the element as often as you need to in order to get any property value you
// like, without having to re-scan the document for it all over again:
var size1 = document.getElementById("width");
var size2 = document.getElementById("height");
var divObj = document.getElementById('totalPrice');
var theForm = document.getElementById("cardform");
var selectedCard1 = theForm.querySelectorAll("[name=selectedcard1]");
var selectedCard2 = theForm.querySelectorAll("[name=selectedcard2]");
var selectedCard3 = theForm.querySelectorAll("[name=selectedcard3]");
var calc = document.querySelector("input[type=button]");
var res = document.querySelector("input[type=reset]");
// Set up event handlers for various DOM elements:
calc.addEventListener("click", calculateTotal);
res.addEventListener("click", reset);
// Create a storage mechanism that holds "keys" and associated "values"
// Arrays can only do this with sequential numeric indexes. Objects, do it
// with string property names.
var card_prices = {};
// No reason to have 3 functions that all do basically the same thing but only
// to different objects. Just have one function that accepts a reference to the
// radiobuttons it needs to work with
function getCardSizePrice(cards){
var cardSizePrice = 0;
// Loop through each radio button in the passed in group
for(var i = 0; i < cards.length; i++) {
//if the radio button is checked
if(cards[i].checked) {
// Lookup the value of the selected radio button in our object and get the
// associate property value
cardSizePrice = card_prices[cards[i].value];
// No reason to continue if we get a match
break;
}
}
// We return the cardSizePrice
return cardSizePrice;
}
function calculateTotal() {
// You didn't have the following code in this funciton, so it was running immediately
// when the page loaded.
// Remember, values that you take out of form elements are strings!
// If you want to treat them as numbers, you should explicitly convert them
// to numbers first:
var s1 = parseFloat(size1.value);
var s2 = parseFloat(size2.value);
var total_size = (s1 * s2) / 10000;
// Set all the property values
card_prices["Round13"] = total_size * 67,
card_prices["Round14"] = total_size * 87,
card_prices["Round17"] = total_size * .05,
card_prices["Round18"] = total_size * .65,
card_prices["Round19"] = total_size * .85,
card_prices["Round20"] = total_size * .95,
card_prices["Round21"] = 2;
card_prices["Round22"] = 5;
card_prices["Round23"] = 5;
// Here we get the total price by calling our function
// Each function returns a number so by calling them we add the values they return together
var cardPrice = getCardSizePrice(selectedCard1) +
getCardSizePrice(selectedCard2) +
getCardSizePrice(selectedCard3);
displayTotal(cardPrice);
}
function displayTotal(price) {
// display the result
divObj.classList.remove("hidden");
divObj.innerHTML = "Total Price For the Card: £" + " " + price.toFixed(2);
}
function reset(){
divObj.innerHTML = "";
}
});
#totalPrice { background-color:#ff0; } // Default style for element
#panel { margin-top: 1em;}
fieldset { margin-bottom:1em; }
<body>
<div id="wrap">
<form action="#" id="cardform">
<div class="cont_order">
<h1>Check Quotes</h1>
<!-- Fieldsets are for logical grouping of form elements. While they do have a
visual component to them, they are primarially for accessibility for
visually impaired. -->
<fieldset>
<legend>Size Of the Card</legend>
<!-- Labels associate with form elements via the "for" attribute and the target
element's "id" attribute. They aren't just for displaying random text.
They are a key aspect of designing for accessibility. You can click/touch the
label and activate the associated form element. -->
<label for="width">Width in cm:</label> <input type="text" id="width">
<label for="height">Height in cm:</label> <input type="text" id="height">
<br><br>
<input type="radio" name="selectedcard1" id="selectedcard1a" value="Round13">
<label for="selectedcard1a" class='radiolabel'>Standard</label>
<input type="radio" name="selectedcard1" id="selectedcard1b" value="Round14">
<label for="selectedcard1b" class='radiolabel'>Toughened</label><br>
</fieldset>
<fieldset>
<legend>Card</legend>
<input type="radio" name="selectedcard2" id="selectedcard2a" value="Round17">
<label for="selectedcard2a" class='radiolabel'>Clear</label>
<input type="radio" name="selectedcard2" id="selectedcard2b" value="Round18">
<label for="selectedcard2b" class='radiolabel'>Frosted</label>
<input type="radio" name="selectedcard2" id="selectedcard2c" value="Round19">
<label for="selectedcard2c" class='radiolabel'>Leaded</label>
<input type="radio" name="selectedcard2" id="selectedcard2d" value="Round20">
<label for="selectedcard2d" class='radiolabel'>White Bar</label>
</fieldset>
<fieldset>
<legend>Frame</legend>
<input type="radio" name="selectedcard3" id="selectedcard3a" value="Round21">
<label for="selectedcard3a" class='radiolabel'>uPVC</label>
<input type="radio" name="selectedcard3" id="selectedcard3b" value="Round22">
<label for="selectedcard3b" class='radiolabel'>Metal</label>
<input type="radio" name="selectedcard3" id="selectedcard3c" value="Round23">
<label for="selectedcard3c" class='radiolabel'>Wood</label>
</fieldset>
<div id="panel">
<input type="button" value="Calculate">
<input type="reset" value="Reset">
<div id="totalPrice"></div>
</div>
</div>
</form>
</div>
I made this calculator http://fernandor80.neocities.org/plancalc/tomx2.html
and it always returns Nan, but once you reload it (with the previously entered inputs), it works...
I've been looking around but I can not figure it out... So I'm here because I really want to get it to work.
here is the code to it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plant Calc V1.2</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins<h2 id="bin45"></h2>
90 count bins<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
<script language="JavaScript">
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr/bed ;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp/45 ;
var bin90 = totalp/90 ;
var nowp = document.getElementById("nowp").value;
var nowb = nowp/ppb ;
function row(){
document.getElementById("ppb").innerHTML = ppb;
}
function total(){
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now(){
document.getElementById("nowb").innerHTML = nowb;
}
</script>
</body>
</html>
Also it doesnt work on mobile devices..I made a pure javascript prompt based calculator for that, but for the purpose of learning i would like some pointers.
I really feel bad about asking a question thats been answered hundreds of times. Sorry, I just had to..
the values of ppr, bed, and ppb are calculated when the page first loads. Thus it's a NaN.
You should consider move at least the data retrieval and calculation inside function row().
One simple way to debug issue like this, if you don't use any IDE, it to press f12 in your browser and open dev mode where you can set break point and check the current value of your variables.
You have dependency over other variable in every function. Instead of using global variables, you can access value in each function.
function row() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
document.getElementById("ppb").innerHTML = ppb;
}
function total() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
var nowp = document.getElementById("nowp").value;
var nowb = nowp / ppb;
document.getElementById("nowb").innerHTML = nowb;
}
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins
<h2 id="bin45"></h2>
90 count bins
<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
It will always NaN because your call values of ppr, bed, and ppb when just first page loaded ! At that page loaded time ,you didn't have any value so NaN getting.So when you click ,you should call that value again ,make it function to call values will be more better...
here I push init() to get value onclick
<script type="text/javascript">
var ppr,bed,ppb,totalp,totalb,bin45,bin90,nowb,nowb;
function init(){
ppr = parseFloat(document.getElementById("ppr").value);
bed = parseFloat(document.getElementById("bed").value);
ppb = ppr/bed ;
totalb = parseFloat(document.getElementById("totalb").value);
totalp = totalb * ppb;
bin45 = totalp/45 ;
bin90 = totalp/90 ;
nowp = document.getElementById("nowp").value;
nowb = nowp/ppb ;
}
function row(){
init();
document.getElementById("ppb").innerHTML = ppb;
}
</script>
I am doing a java script application that calculates Miles driven / gallons used and gallons used* price per gallon. I have two problems:
1) when I enter all the values price per gallon adds a another zero automatically. For example 40, becomes 400.
2) I am looking to write the result of both calculations underneath the button.
If anyone can give me guidance or help I would really appreciate it.
<!DOCTYPE
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
}
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value); //alert(miles);
var gallons = parseFloat($("gallons").value);
var costGallon = document.getElementById("costGallon").value;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
}
else {
var mpg = miles/gallons;
var costGallon = gallons*costGallon;
$("costGallon").value=costGallon.toFixed(2);
//alert("your total is" +mpg );
alert("your total new is " + costGallon);
//cost of trip = gallons used * price per gallon
}
}
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
}
</script>
</head>
<section>
<body>
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br><br>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br><br>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br><br>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span>
</section>
</body>
</html>
Can you give me an example of where it does that? I copy pasted your code and for me it gives the correct values. From what I understand the only thing you are writting into the cost per gallon field is the gallons used times the price per gallon. An that seems to be working fine.
If you can provide me with a example calculation you want to achive i'd be happy to help.
On another note, i suggest not using the same variable again in line 27 that you used to hold the DOM object of the input field. Also toFixed does not change the variable you used it on but return a new variable so instead remove that in line 28 and have line 27 look something like this:
var newVarNameIsBoss = (gallons*costGallon).toFixed(2);
Hope this helps
revised code
<!DOCTYPE html> <!-- scorrect doctype-->
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
};//remember that a var decleration always ends with a ; even if it's a function
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value), //alert(miles);
gallons = parseFloat($("gallons").value),
costGallon = document.getElementById("costGallon").value,
mpg,totalCost;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
} else {
mpg = miles/gallons;
totalCost = (gallons*costGallon).toFixed(2);
costGallon.value=totalCost;
alert("your total new is " + totalCost);
$('totalMpg').innerHTML = String(mpg.toFixed(2)) + " Miles per Gallon";
}
};//remember that a var decleration always ends with a ; even if it's a function
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
};//remember that a var decleration always ends with a ; even if it's a function
</script>
</head>
<body>
<section> <!-- section bellow the body tag-->
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br/><br/>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br/><br/>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br/><br/>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span></p><!--closing p tag here-->
</section>
</body>
</html>