if statement not returning a value - javascript

I am trying to make a simple price calculator based on a total area value calculated by user input fields. So far most all of the program operates correctly, except the if statement that will determine the price rate based on the total sqin, does not return a value. At this point it is only setup for the Economy selection of the first drop down. The other selections are set to a constant value and work as expected. Any help with this is greatly appreciated as I am still a javascript novice.
/*eslint-env browser*/
var mytotalsq;
function getEconPrice() {
var EconPrice = 0;
if (mytotalsq <= 199) {
return EconPrice.value = .40;
}
if (mytotalsq >= 200 && mytotalsq <= 299) {
return EconPrice.value = .22;
}
return EconPrice;
}
var vinyl_prices = new Array();
vinyl_prices["None"] = 0;
vinyl_prices["Econ"] = getEconPrice();
vinyl_prices["Inter"] = .25;
vinyl_prices["HPerf"] = .35;
vinyl_prices["HiTack"] = .75;
vinyl_prices["Ref"] = .75;
var laminate_prices = new Array();
laminate_prices["None"] = 1;
laminate_prices["NoLam"] = 1;
laminate_prices["StanLam"] = 1.43;
laminate_prices["HPLam"] = 1.7;
function getStickerPrice() {
var StickerPrice = 0;
var theForm = document.forms["stickerform"];
var selectedVinyl = theForm.elements["vinyl"];
StickerPrice = vinyl_prices[selectedVinyl.value];
return StickerPrice;
}
function getLaminatePrice() {
var LaminatePrice = 0;
var theForm = document.forms["stickerform"];
var selectedLaminate = theForm.elements["laminate"];
LaminatePrice = laminate_prices[selectedLaminate.value];
return LaminatePrice;
}
function calculateTotal() {
var myheight = document.getElementById('height').value;
var mywidth = document.getElementById('width').value;
var myquan = document.getElementById('quan').value;
var totalsq = document.getElementById('totalsq');
mytotalsq = mywidth * myheight * myquan;
totalsq.value = mytotalsq;
var stickerPrice = mytotalsq * getStickerPrice() * getLaminatePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total $" + stickerPrice;
}
<!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>RMSticker Pricing</title>
<script type="text/javascript" src="js/stickercalc.js"></script>
<link href="css/sticker.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrap">
<form action="" id="stickerform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>RMSticker</legend>
<label>Height</label>
<input id="height" type="text" />
<label>Width</label>
<input id="width" type="text" />
<label>Quantity</label>
<input id="quan" type="text" oninput="calculateTotal()" />
<input id="totalsq" name="totalsq" type="text" />
<br/><br/>
<label>Vinyl</label>
<select id="vinyl" name='vinyl' onchange="calculateTotal()">
<option value="None">Select Vinyl</option>
<option value="Econ">Economy</option>
<option value="Inter">Intermediate</option>
<option value="HPerf">High Performance</option>
<option value="HiTack">High Tack</option>
<option value="Ref">Reflective</option>
</select>
<br/><br/>
<label>Laminate</label>
<select id="laminate" name='laminate' onchange="calculateTotal()">
<option value="None">Select Laminate</option>
<option value="NoLam">None</option>
<option value="StanLam">Standard</option>
<option value="HPLam">High Performance</option>
</select>
<br/><br/>
<label>Select Finish</label>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Matte" onclick="calculateTotal()" />Matte</label><br/>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Satin" onclick="calculateTotal()" />Satin(Only available on laminated stickers)</label><br/>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Gloss" onclick="calculateTotal()" />Gloss</label><br/>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>

The main issue is that the lines that set up your new array and attempt to populate it run immediately (before the user has had a chance to enter any data) and so your array is empty when you attempt to get information out of it.
Moving the lines that populate the arrays (but not the lines that declare the arrays) into the calculate function solves the problem.
/*eslint-env browser*/
var mytotalsq;
function getEconPrice() {
var EconPrice = 0;
if (mytotalsq <= 199) {
return EconPrice.value = .40;
}
if (mytotalsq >= 200 && mytotalsq <= 299) {
return EconPrice.value = .22;
}
return EconPrice;
}
function getStickerPrice() {
var StickerPrice = 0;
var theForm = document.forms["stickerform"];
var selectedVinyl = theForm.elements["vinyl"];
StickerPrice = vinyl_prices[selectedVinyl.value];
return StickerPrice;
}
function getLaminatePrice() {
var LaminatePrice = 0;
var theForm = document.forms["stickerform"];
var selectedLaminate = theForm.elements["laminate"];
LaminatePrice = laminate_prices[selectedLaminate.value];
return LaminatePrice;
}
var vinyl_prices = new Array();
var laminate_prices = new Array();
function calculateTotal() {
vinyl_prices["None"] = 0;
vinyl_prices["Econ"] = getEconPrice();
vinyl_prices["Inter"] = .25;
vinyl_prices["HPerf"] = .35;
vinyl_prices["HiTack"] = .75;
vinyl_prices["Ref"] = .75;
laminate_prices["None"] = 1;
laminate_prices["NoLam"] = 1;
laminate_prices["StanLam"] = 1.43;
laminate_prices["HPLam"] = 1.7;
var myheight = document.getElementById('height').value;
var mywidth = document.getElementById('width').value;
var myquan = document.getElementById('quan').value;
var totalsq = document.getElementById('totalsq');
mytotalsq = mywidth * myheight * myquan;
totalsq.value = mytotalsq;
var stickerPrice = mytotalsq * getStickerPrice() * getLaminatePrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total $" + stickerPrice;
}
<!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>RMSticker Pricing</title>
<script type="text/javascript" src="js/stickercalc.js"></script>
<link href="css/sticker.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrap">
<form action="" id="stickerform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>RMSticker</legend>
<label>Height</label>
<input id="height" type="text" />
<label>Width</label>
<input id="width" type="text" />
<label>Quantity</label>
<input id="quan" type="text" oninput="calculateTotal()" />
<input id="totalsq" name="totalsq" type="text" />
<br/><br/>
<label>Vinyl</label>
<select id="vinyl" name='vinyl' onchange="calculateTotal()">
<option value="None">Select Vinyl</option>
<option value="Econ">Economy</option>
<option value="Inter">Intermediate</option>
<option value="HPerf">High Performance</option>
<option value="HiTack">High Tack</option>
<option value="Ref">Reflective</option>
</select>
<br/><br/>
<label>Laminate</label>
<select id="laminate" name='laminate' onchange="calculateTotal()">
<option value="None">Select Laminate</option>
<option value="NoLam">None</option>
<option value="StanLam">Standard</option>
<option value="HPLam">High Performance</option>
</select>
<br/><br/>
<label>Select Finish</label>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Matte" onclick="calculateTotal()" />Matte</label><br/>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Satin" onclick="calculateTotal()" />Satin(Only available on laminated stickers)</label><br/>
<label class='radiolabel'><input type="radio" name="selectedfinish" value="Gloss" onclick="calculateTotal()" />Gloss</label><br/>
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
</body>
</html>

Related

how to show the output after the form submit in JavaScript

How to edit the code so that the function calculateTotal can run when the submit button is pressed, and the output is how after the submit button press but not directly show to people by keep adding.
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*(5455/12);
elec["elec2"] = 150*(5455/12);
elec["elec3"] = 200*(5455/12);
elec["elec4"] = 250*(5455/12);
elec["elec5"] = 300*(5455/12);
elec["elec6"] = 350*(5455/12);
elec["elec7"] = 400*(5455/12);
elec["elec8"] = 450*(5455/12);
elec["elec9"] = 500*(5455/12);
elec["elec10"] = 550*(5455/12);
elec["elec11"] = 600*(5455/12);
elec["elec12"] = 650*(5455/12);
elec["elec13"] = 700*(5455/12);
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste()
{
var mustwaste=0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if(waste.checked==true)
{
mustwaste=(692/12);
}
return mustwaste;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste()
{
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++)
{
if (cw[i].type == 'checkbox')
{
if (cw[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
var error = document.getElementById("error")
if (!vwaste())
{
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5&nbsp</label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' onclick="calculateTotal()" /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu">&nbspAluminium and Steel&nbsp&nbsp</label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas">&nbspPlastic&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
Move the call to calculateTotal() to the form's onsubmit instead of doing it in all the onclick.
Also take calls to it out of other functions.
var person = [];
person["person1"] = 1;
person["person2"] = 2;
person["person3"] = 3;
person["person4"] = 4;
person["person5"] = 5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100 * (5455 / 12);
elec["elec2"] = 150 * (5455 / 12);
elec["elec3"] = 200 * (5455 / 12);
elec["elec4"] = 250 * (5455 / 12);
elec["elec5"] = 300 * (5455 / 12);
elec["elec6"] = 350 * (5455 / 12);
elec["elec7"] = 400 * (5455 / 12);
elec["elec8"] = 450 * (5455 / 12);
elec["elec9"] = 500 * (5455 / 12);
elec["elec10"] = 550 * (5455 / 12);
elec["elec11"] = 600 * (5455 / 12);
elec["elec12"] = 650 * (5455 / 12);
elec["elec13"] = 700 * (5455 / 12);
function getNumberperson() {
var numberperson = 0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for (var i = 0; i < selectedPerson.length; i++) {
if (selectedPerson[i].checked) {
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal() {
var electotal = 0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function waste() {
var mustwaste = 0;
var theForm = document.forms["energyform"];
var waste = theForm.elements["waste"];
if (waste.checked == true) {
mustwaste = (692 / 12);
}
return mustwaste;
}
function recyclealu() {
var recyclealu = 0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if (yesalu.checked == true) {
recyclealu = -89.38;
}
return recyclealu;
}
function recycleplas() {
var recycleplas = 0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if (yesplas.checked == true) {
recycleplas = -35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('.recycle');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
}
function calculateTotal() {
var totalco = getNumberperson() * getElectotal() + waste() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco.toFixed(2);
}
//add a function to hide the result on page loading at the start
function hideTotal() {
document.getElementById('totalConsumption').innerHTML = "0";
}
function vwaste() {
var cw = document.getElementsByName('waste');
for (var i = 0; i < cw.length; i++) {
if (cw[i].type == 'checkbox') {
if (cw[i].checked) {
return true
}
}
}
return false;
}
function allvalidate() {
var error = document.getElementById("error")
if (!vwaste()) {
// Changing content and color of content
error.textContent = "Waste must be select"
error.style.color = "red"
return false;
}
return true;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="calculateTotal();return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label>Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1"/>1&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" />2&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" />3&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" />4&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" />5&nbsp</label>
<br/>
<label><i class="fa fa-flash"></i>Waste</label>
<input type="checkbox" id="waste" name='waste' /><span id="error"></span>
<hr><label><i class="fa fa-flash"></i>Energy Consumption Per Month</label></hr>
<br/>
<label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
<select id="electricity" name='electricity' >
<option value="elecuse">0kWh</option>
<option value="elec1">100kWh</option>
<option value="elec2">150kWh</option>
<option value="elec3">200kWh</option>
<option value="elec4">250kWh</option>
<option value="elec5">300kWh</option>
<option value="elec6">350kWh (Avg US)</option>
<option value="elec7">400kWh (Avg MY)</option>
<option value="elec8">450kWh</option>
<option value="elec9">500kWh (Avg AS)</option>
<option value="elec10">550kWh</option>
<option value="elec11">600kWh</option>
<option value="elec12">650kWh</option>
<option value="elec13">700kWh</option>
</select>
<hr><label><i class="fa fa-flash"></i>Recycle </label></hr>
<br/>
<label for='yesalu' class="alu">&nbspAluminium and Steel&nbsp&nbsp</label>
<input type="checkbox" id="yesalu" name='yesalu' class="recycle" />
<br/>
<label for='yesplas' class="plas">&nbspPlastic&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
<input type="checkbox" id="yesplas" name='yesplas' class="recycle" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
<label>pounds</label>
<div>US Household average is 21,820 lbs per year.</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>

Why does form calculation return Nan?

Apologies as I am relatively new to Javascript.
I have a form returning 2 values, and the first value (totalprice) works fine.
For the second value the page has to be refreshed or returns a Nan error
My Javascript code is:
var pallet_prices = [3.5, 2.75, 2.60, 2.50, 2.25, 2.00];
var order_price = [1.30, 1.15, 1.10, 1.05, 1.00, 0.93];
var extra_cost = [0.55, 0.45, 0.40, 0.40, 0.38, 0.35];
var items_quantity = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var item_charge = 0;
var item_index = 0;
var weekly_quantity = 0;
var item_charge = parseFloat(item_charge);
var item_index = parseFloat(item_index);
var weekly_quantity = parseFloat(weekly_quantity);
// uncertain if these variables need to be converted to numbers ...
// var pallet_prices = parseFloat(pallet_prices);
// var order_price = parseFloat(order_price);
// var extra_cost = parseFloat(extra_cost);
// var items_quantity = parseFloat(items_quantity);
function clear_radio_buttons() {
var inp = document.getElementsByTagName('input');
for (var i = inp.length - 1; i >= 0; i--) {
if ('radio' === inp[i].type) inp[i].checked = false;
}
}
function reset_select_fields() {
var inp = document.getElementsByTagName('input');
for (var i = inp.length - 1; i >= 0; i--) {
if ('select' === inp[i].type) inp[i].checked = false;
}
}
function getpalletPrice() {
var palletPrice = 0;
var pallet_index = 0;
var theForm = document.forms["fulfilment"];
var nopallets = theForm.elements["nopallets"];
for (var i = 0; i < nopallets.length; i++) {
if (nopallets[i].checked) {
pallet_index = i; //Get index number of pallet prices array for this selection
break;
}
}
return pallet_index;
}
function get_no_orders() {
//var week_orders;
var week_orders_index = 0;
var theForm = document.forms["fulfilment"];
var number_orders = theForm.elements["number_orders"];
for (var i = 0; i < number_orders.length; i++) {
if (number_orders[i].checked) {
week_orders_index = i;
break;
}
}
return week_orders_index;
}
function get_items_per_order() {
var items_quantity = 0;
var theForm = document.forms["fulfilment"];
var no_of_items = theForm.elements["no_of_items"];
for (var i = 0; i < no_of_items.length; i++) {
if (no_of_items[i].checked) {
items_quantity = no_of_items[i].value;
break;
}
}
return items_quantity;
}
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns an index number so by calling them we can add the values they represent together
var pallet_index = getpalletPrice(); // Get the index number of the price array
palletPrice = pallet_prices[pallet_index]; // Get the charge from the pallet_prices array
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
// divobj.innerHTML = "Storage Price per Pallet £"+palletPrice; // Display the pallet storage charge
divobj.innerHTML = "Storage Price per Pallet £" + parseFloat(palletPrice).toFixed(2); // Display the pallet storage charge
// Note this all falls down if the result is not displayed at this point
// Now get the charge for the number of orders per week and the extra cost per item for this quantity of orders
weekly_order_quantity = get_no_orders();
extra_cost = extra_cost[weekly_order_quantity];
order_price = order_price[weekly_order_quantity];
//items_quantity = get_items_per_order();
// Now get the number of items for the order
//items_index = get_items_per_order(); // This is not returning a valid number
//items_index = 5; // Test with a valid number
//items_index = document.getElementById("no_of_items").value;
// Calculate total ordering charge
//
week_orders = 0; // Define the display variable
/* // week_orders is calculated by the formula
// week_orders = Charge for Volume Quantity + (No of Items per order quantity - 1) * Extra Cost for Number of Orders per week Charge
// e.g 55 items: Charge for 55 Orders per week = 1.05, Items per Individual Order Quantity = 8, Extra Cost for 55 Orders per week = 0.40
// week_orders = £1.05 + (8-1) * £0.40 = £1.05 + 7 * £0.40 = £3.85
*/
//week_orders = order_price; // Test - Variable is defined & usable
//week_orders = extra_cost; // Test - Variable is defined & usable
// week_orders = items_index; // Test - Variable not defined/working
//Final calculation for display Comment out for testing!!!
items_index = document.getElementById("no_of_items").value;
week_orders = order_price + extra_cost * (items_index - 1);
// NOTE WE NEED TO RESET THE FORM AFTER DISPLAY OR VARIABLES NOT VALID FOR CALCULATION
//display the result
var divobj = document.getElementById('totalPrice1');
divobj.style.display = 'block';
// divobj.innerHTML = "Price per Order £"+week_orders; // Display the total Order cost
divobj.innerHTML = "Price per Order £" + parseFloat(week_orders).toFixed(2); // Display the total Order cost
reset_select_fields();
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
function clear_screen() {
location.reload();
}
function hideTotal1() {
var divobj = document.getElementById('totalPrice1');
divobj.style.display = 'none';
}
function hideTotals() {
hideTotal();
hideTotal1();
}
<!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>Fulfilment Calculator</title>
<script type="text/javascript" src="js/formcalculations.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="styles/fulfilment.css" rel="stylesheet" type="text/css" />
</head>
<body onLoad='hideTotals()' ;>
<div id="wrap">
<div>
<form action="" id="fulfilment" onsubmit="return false;">
<div class="cont_order">
<fieldset>
<legend>Calculate Pallet Storage Price</legend>
<label>Select Number of Pallets Stored</label>
<label class='radiolabel'><input type="radio" name="nopallets" value="1" onclick="calculateTotal()" />1 to 5 stored per week</label><br/>
<label class='radiolabel'><input type="radio" name="nopallets" value="6" onclick="calculateTotal()" /> 6 to 25 stored per week</label><br/>
<label class='radiolabel'><input type="radio" name="nopallets" value="26" onclick="calculateTotal()" /> 26 to 50 stored per week</label><br/>
<label class='radiolabel'><input type="radio" name="nopallets" value="51" onclick="calculateTotal()" /> 51 to 100 stored per week</label><br/>
<label class='radiolabel'><input type="radio" name="nopallets" value="101" onclick="calculateTotal()" /> 101 to 200 stored per week</label><br/>
<label class='radiolabel'><input type="radio" name="nopallets" value="200" onclick="calculateTotal()" /> 200+ stored per week</label><br/>
<br/>
<div id="totalPrice"></div>
</fieldset>
<fieldset>
<legend>How many items on your order?</legend>
<select id="no_of_items" name='no_of_items'>
<option value="None" autofocus selected disabled>Select No. of Items</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br/>
</fieldset>
<fieldset>
<legend>How many orders each week?</legend>
<label>Number of Orders per Week</label>
<label class='radiolabel'><input type="radio" name="number_orders" value="1" onclick="calculateTotal()" />1 to 10 orders per week</label><br/>
<label class='radiolabel'><input type="radio" name="number_orders" value="11" onclick="calculateTotal()" /> 11 to 25 orders per week</label><br/>
<label class='radiolabel'><input type="radio" name="number_orders" value="26" onclick="calculateTotal()" /> 26 to 50 orders per week</label><br/>
<label class='radiolabel'><input type="radio" name="number_orders" value="51" onclick="calculateTotal()" /> 51 to 100 orders per week</label><br/>
<label class='radiolabel'><input type="radio" name="number_orders" value="101" onclick="calculateTotal()" /> 101 to 200 orders per week</label><br/>
<label class='radiolabel'><input type="radio" name="number_orders" value="201" onclick="calculateTotal()" /> 201+ orders per week</label><br/>
<br/>
<div id="totalPrice1"></div>
<a onClick="window.location.reload()">Refresh</a>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<br>
<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="calculateTotal3()" />
<input type </form>
</div>
<!--End of wrap-->
</body>
</html>
Any help would be much appreciated
The first part of the form works as expected, but the sceond, althought the maths is cirrect gives a NaN unless the page is refreshed.
I think there is a problem here:
items_index = document.getElementById("no_of_items").value;
week_orders = order_price + extra_cost * (items_index - 1);
items_index is a string...
(items_index - 1) will return NaN if items_index is not a number-in-a-string.
Could also be if order_price or extra_cost are not numbers/number-in-a-string.

Implementing Submit action in javascript

I am new to javascript..I am facing some problems while trying to implement form submit action onclick using javascript..
The problem is when I implement all the validation checks using if-else conditions ..The function dose not produce any result..
[] 1[]2
I have implemented various validation check and tried to capture all possible form elements with different conditions..But I am failing when I am implementing validation check..otherwise the code works -I cannot figure out what is the problem..
Here is the code:
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNAN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNAN(ag) || ag.parseInt() > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
</head>
<body style="background:pink;">
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>
The first error is at these lines
var nam=document.getElementById("student_name").value;
if(nam.value.length==0 || !(isNAN(nam)) || nam.value.length>20){
nam="Invalid";
}
nam is the value of the input again doing nam.value will throw an error
Secondly isNAN is not a javascript inbuilt function. Case matters while using in build function , it has to be isNaN
Thirdly ag.parseInt() is wrong. Instead it has to be parseInt(ag,10) where 10 is the radix
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNaN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNaN(ag) || parseInt(ag, 10) > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
This might help you
function submitForm()
{
var nam = document.getElementById("student_name").value;
if (!(nam) || nam.length > 20)
{
alert("please Select a valid name");
return false;
}
var ag = document.getElementById("student_age").value;
if (!(ag) || ag > 100)
{
alert("please Select a valid age");
return false;
}
var gender = "";
if(!document.getElementById("g1").checked && !document.getElementById("g2").checked )
{
alert("please Select gender");
return false;
}
else
{
if(document.getElementById("g1").checked)
{
gender = document.getElementById("g1").value;
}
else
{
gender = document.getElementById("g2").value;
}
}
var cty = document.getElementById("city").value;
if (!(cty) || cty=="Default")
{
alert("please Select a city");
return false;
}
var hobbies ="";
if(!document.getElementById("h1").checked && !document.getElementById("h2").checked && !document.getElementById("h3").checked)
{
alert("please Select hobby");
return false;
}
else
{
var inputElements = document.getElementsByName("cbox");
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
var value=" "+ inputElements[i].value;
hobbies +=value;
}
}
}
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body style="background:pink;">
<div id="body">
<form action="#" method="post" onsubmit="return false">
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Default">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label>
<input type="checkbox" id="h1" name="cbox" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
<input type="submit" value="Submit" onclick="submitForm()">
</form>
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>

What am I missing in my JavaScript code?

I'm new to JavaScript and I’m having issues trying to create a drop down list unit converter. The project calls for the code to convert miles to feet, Celsius to Fahrenheit and pounds to grams. The issue is when I enter the values the output is way off.
No matter what number I enter or unit I select I get the same result of 14514.944, instead of the appropriate (5280 feet, 33.8°, 453.592g, etc.). If I double click the submit button I get 62573043513.9154, triple click 269748534086686000, etc.
I know I’m missing something in the convert_unit function, but I’m not sure what. I’ve tried adding and removing various code and nothing is working.
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value)
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
<form>
<fieldset>
<label id="enter">Numeric Value</label>
<p>
<input type="number" placeholder="Enter Value" name=" " value=" " id="numInput" />
</p>
</fieldset>
<fieldset><label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onClick="convert_unit()";>Convert</button>
</fieldset>
<fieldset><label id="results">Results</label>
<p>
<input type="number" placeholder="Results" name="to_unit" id="numOutput" readonly /></p>
</fieldset>
</form>
Both of your variables are named numInput:
var numInput = document.getElementById("numInput");
var numInput = document.getElementById("numOutput");
I'm guessing your second one should be numOutput. Also, there's no need to redefine these variables in JS unless you want to make it explicitly known what they are. HTML elements with IDs are already available in the global scope based on their ID name (with some caveats). In this case you could simply use numInput and numOutput throughout your program and it would still work even without these two lines.
i found 2 problems in your code.
The first is that in line 4 of the script, you overwrite the input of variable "numInput" with "numOutput" element. (Rename to 'numOutput')
The second problem is that, when script is loaded on page, the elements is not yet instanced. To solve that you can put the import tag right before </body> or add variables definition inside the function.
PS: Don't forget to use semicolons after every statement;
Jah Bless =)
index.html
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<fieldset>
<label id="enter">Pounds to Grams</label>
<p><input placeholder="Enter Value" name=" " value=" " id="numInput" type="number"></p>
</fieldset>
<fieldset>
<label>Conversion Menu</label>
<p>
<select id="" name="" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select>
</p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value=" " onclick="convert_unit()" ;="">Convert</button>
</fieldset>
<fieldset>
<label id="results">Pounds to Grams</label>
<p><input placeholder="Results" name="to_unit" id="numOutput" readonly="" type="number"></p>
</fieldset>
</form>
<script src="script.js"></script>
</body>
</html>
script.js
function convert_unit() {
var numInput = document.getElementById('numInput');
var numOutput = document.getElementById('numOutput');
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
numOutput.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
numOutput.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("enter").innerHTML = x;
document.getElementById("results").innerHTML = x;
}
Your code corrected, customized and working perfectly!
var numInput = document.getElementById("numInput");
var numOutput = document.getElementById("numOutput");
var feet = document.getElementById("feet");
var fahrenheit = document.getElementById("fahrenheit");
var grams = document.getElementById("grams");
function convert_unit() {
if(numInput.value === "") {
if(confirm("No value inputed to convert! Consider default 1 unit?")) {
numInput.value = 1;
}
}
if(getSelectedUnitToConvert("conversion_type") == null) {
if(confirm("No conversion unit selected! Consider default Miles to Feet?")) {
document.getElementById("conversion_type").selectedIndex = 0;
}
}
if(getSelectedUnitToConvert("conversion_type") == "Miles to Feet") {
numOutput.value=numInput.value;
numOutput2.value=(5280*numInput.value);
var x = document.getElementById("feet").label;
document.getElementById("result1").innerHTML = "Miles";
document.getElementById("result2").innerHTML = "Feet";
} else if(getSelectedUnitToConvert("conversion_type") == "Celcius to Fahrenheit") {
numOutput.value=numInput.value;
numOutput2.value=(1.8*numInput.value)+32;
var x = document.getElementById("fahrenheit").label;
document.getElementById("result1").innerHTML = "Celcius";
document.getElementById("result2").innerHTML = "Fahrenheit";
} else if(getSelectedUnitToConvert("conversion_type") == "Pounds to Grams") {
numOutput.value=numInput.value;
numOutput2.value=(453.592*numInput.value);
var x = document.getElementById("grams").label;
document.getElementById("result1").innerHTML = "Pounds";
document.getElementById("result2").innerHTML = "Grams";
}
}
function getSelectedUnitToConvert(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1) {
return null;
}
return elt.options[elt.selectedIndex].text;
}
div {
margin: 5px;
}
<form>
<fieldset>
<label id="enter">Value to Convert</label>
<p><input type="number" placeholder="Enter Value" value="" id="numInput" /></p>
</fieldset>
<fieldset><label>Units for Conversion</label>
<p><select id="conversion_type" size="3">
<option id="feet" name="Miles to Feet">Miles to Feet</option>
<option id="fahrenheit" name="Celcius to Fahrenheit">Celcius to Fahrenheit</option>
<option id="grams" name="Pounds to Grams">Pounds to Grams</option>
</select></p>
</fieldset>
<fieldset>
<button type="button" id="mybutton" value="" onclick="convert_unit();">Convert</button>
</fieldset>
<fieldset><label id="results">Conversion Result:</label>
<p>
<div>
<input placeholder="Original Value" name="to_unit" id="numOutput" readonly />
<label id="result1"></label>
</div>
<div>
<input placeholder="Conversion Result" name="to_unit2" id="numOutput2" readonly />
<label id="result2"></label>
</div>
</p>
</fieldset>
</form>

Adding radio and check box totals?

I'm designing a online car shop as part of a small exercise. Everything going smoothly except for the total price. I want the selections to add on to the running total, depending on what radio button and check box I select, rather than each time a selection is made, the value of that selection accumulating on to my total. I hope I made explained that properly, I'd appreciate any help anyone can give!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Configure Your GT Sports Car</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<header>
<h1>Configure your GT Super Sportscar</h1>
</header>
</div></div></div>
<form name="SportsCar" id="SportsCar">
<p>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<h3>Configuration</h3>
<input type="radio" name="format" id = "Manual" value="27790.00">
<label for = "Manual">GT Manual - €27,790.00</label>
<br>
<input type="radio" name="format" id = "Automatic" value="28590.00">
<label for = "Automatic">GT Automatic - €28,590.00</label>
<br>
<input type="radio" name="format" id = "Smanual" value="32455.00">
<label for = "Smanual">GT-S Manual - €32,455.00</label>
<br>
<input type="radio" name="format" id = "Sautomatic" value="33155.00">
<label for = "Sautomatic">GT-S Automatic - €33,155.00</label>
<br>
</div>
<div class="col-md-6">
<h3>Car Colours</h3>
<label for = "colour" >Please select a colour</label>
<select name="colour" id="colour">
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="silver">Silver</option>
<option value="white">White</option>
</select>
<img id="carImage" img src="images/black.jpg" alt="target_blank">
</div></div></div></div>
<div class="row">
<div class="col-md-12">
<h3>Factory Options</h3>
<input type="radio" name="fOptions" id="combo1" value="1235.00">
<label for="combo1">Option Combo 1 - €1,235.00</label>
<br>
(Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="combo2" value="3354.00">
<label for="combo2">Option Combo 2 - €3,354.00</label>
<br>
(Rear spoiler & Fog Lamps, Key-less Entry, Power Tilt & Slide Moonroof, Power windows, Doors, Cruise Control)
<br>
<input type="radio" name="fOptions" id="noExtras" value="0.00">
<label for="noExtras">No Extras - €0</label>
</div></div>
<br>
<div class="row">
<div class="col-md-12">
<h3>Dealer Options</h3>
<input type="checkbox" name="dealer" id="autochanger" value="550.00">
<label for = "auto-changer">CD Auto-Changer - €550.00</label>
<br>
<input type="checkbox" name="dealer" id="security" value="399.00">
<label for = "security">VIP Security System - €399.00</label>
<br>
<input type="checkbox" name="dealer" id="mirror" value="295.00">
<label for = "mirror">Auto Dimming Mirror - €295.00</label>
<br>
</div></div>
<div class="row">
<div class="col-md-12">
<br>
<label for="total" class="control-label col-md-2">Total Cost</label>
<input type="text" name="total" id="total" maxlength="3" readonly>
</div></div>
</p>
</form>
</div>
</body>
<script type="text/javascript">
var source = new Array();
window.addEventListener("load", preLoad, false);
function preLoad(){
source[0]="images/black.jpg";
source[1]="images/blue.jpg";
source[2]="images/red.jpg";
source[3]="images/silver.jpg";
source[4]="images/white.jpg";
}
carColour = document.getElementById("colour");
function handleColour(){
if(carColour.selectedIndex==0)
{
theImage.src=source[0];
}
else if(carColour.selectedIndex==1)
{
theImage.src=source[1];
}
else if(carColour.selectedIndex==2)
{
theImage.src=source[2];
}
else if(carColour.selectedIndex==3)
{
theImage.src=source[3];
}
else if(carColour.selectedIndex==4)
{
theImage.src=source[4];
}
}
theImage=document.getElementById("carImage");
carColour.addEventListener("click", handleColour, false);
</script>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/calculate.js"></script>
</html>
Javascript
function formatCurrency(num) {
num = num.toString().replace(/\€|\,/g,'');
if(isNaN(num))
{num = "0";}
sign = (num == (num = Math.abs(num)));
num = num.toFixed(2);
elements= num.split(".");
num = elements[0];
cents = elements[1];
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
{num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*0+3));}
return (((sign)?'':'-') + '€' + num + '.' + cents)
}
window.addEventListener("load", handleLoad, false);
function handleLoad(){
runningTotal=parseInt(document.getElementById("Manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
cars = document.getElementById("Manual");
cars.addEventListener("click", handleConfig, false);
function handleConfig(){
if(manual.checked){
runningTotal = parseInt(document.getElementById("manual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Automatic");
cars.addEventListener("click", handleConfigOne, false);
function handleConfigOne(){
if(Automatic.checked){
runningTotal = parseInt(document.getElementById("Automatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Smanual");
cars.addEventListener("click", handleConfigTwo, false);
function handleConfigTwo(){
if(Smanual.checked){
runningTotal = parseInt(document.getElementById("Smanual").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
cars = document.getElementById("Sautomatic");
cars.addEventListener("click", handleConfigThree, false);
function handleConfigThree(){
if(Sautomatic.checked){
runningTotal = parseInt(document.getElementById("Sautomatic").value);
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var option = document.getElementById("combo1");
option.addEventListener("click", handleClick, false);
function handleClick(){
if(combo1.checked)
{
list=parseInt(document.getElementById("combo1").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var factory = document.getElementById("combo2");
factory.addEventListener("click", handleExtrasTwo, false);
function handleExtrasTwo(){
if(combo2.checked)
{
list=parseInt(document.getElementById("combo2").value);
runningTotal+=list;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var extras = document.getElementById("noExtras");
extras.addEventListener("click", handleNoExtras, false);
function handleNoExtras(){
if(noExtras.checked)
{
var noList=parseInt(document.getElementById("noExtras").value);
runningTotal += noList;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptions = document.getElementById("autochanger");
dealerOptions.addEventListener("click", handleOptions,false);
function handleOptions(){
if(autochanger.checked)
{
autoChange=parseInt(document.getElementById("autochanger").value);
runningTotal +=autoChange;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOption = document.getElementById("security");
dealerOption.addEventListener("click", handleOptionsTwo,false);
function handleOptionsTwo(){
if(security.checked)
{
secure=parseInt(document.getElementById("security").value);
runningTotal+=secure;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
var dealerOptionThree = document.getElementById("mirror");
dealerOptionThree.addEventListener("click", handleOptionThree,false);
function handleOptionThree(){
if(mirror.checked)
{
mirror=parseInt(document.getElementById("mirror").value);
runningTotal += mirror;
document.getElementById("total").value=formatCurrency(runningTotal);
}
}
As you already have jquery included in your page, you should use it. It makes your life so much simpler. Using your code as a base, I've created a simple method to sum the values of the selected elements (radio or checkbox), and display it on the total textbox.
Then you will not have to put all those click events.
Check it out: (see the running example on this fiddle: http://jsfiddle.net/b3p4r/)
$("input").change(function() {
var total = 0;
$("input").each(function() {
if($(this).is(":checked"))
total += parseFloat($(this).val());
});
$("#total").val(formatCurrency(total));
});

Categories

Resources