Why does form calculation return Nan? - javascript

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.

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>

JavaScript Total Price List Not Displaying

Within my set of price lists, I have radio buttons to select one option. That option then gets added to the total. I then want to have a number of checkboxes that you can select additional multiple options. However, the script only returns £NaN instead of the actual figure. As far as I am aware, I have assigned prices under the array correctly.
I'm stumped and can't find out why it isn't calculating.
As requested, I've included the code in one element. (full code is on codepen: https://codepen.io/Amnesia180/pen/RwKQOKP)
var burger_prices = new Array();
burger_prices["1x3oz"]=2;
burger_prices["2x3oz"]=3;
function getBurgerSizePrice()
{
var burgerSizePrice=0;
var theForm = document.forms["custom-burger"];
var selectedBurger = theForm.elements["burger-meat"];
for(var i = 0; i < selectedBurger.length; i++)
{
//if the radio button is checked
if(selectedBurger[i].checked)
{
burgerSizePrice = burger_prices[selectedBurger[i].value];
break;
}
}
return burgerSizePrice;
}
var burger_Sauces = new Array();
burger_Sauces["burgersauce"]=2;
burger_Sauces["spicyketchup"]=2;
function getBurgerSaucesPrice() {
var BurgerSaucesPrice = 0;
var theForm = document.forms["custom-burger"];
var selectedSauces = theForm.elements["selectedSauces"];
for (var i = 0; i < selectedSauces.length; i++) {
if(selectedSauces[i].checked){
BurgerSaucesPrice += burger_Sauces[selectedSauces[i].value];
break;
}
}
return BurgerSaucesPrice;
}
function calculateTotal()
{
var burgerPrice = getBurgerSizePrice() + getBurgerSaucesPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Burger £"+burgerPrice;
}
<section class="burgerform">
<form action="" id="custom-burger" onsubmit="return false;">
<fieldset>
<legend>Create your Burger Box!</legend>
<label>Meat</label><p/>
<input type="radio" name="burger-meat" value="1x3oz"
onclick="calculateTotal()" />
1 x 3oz Beef Patty (£2)<br/>
<input type="radio" name="burger-meat" value="2x3oz"
onclick="calculateTotal()" />
2 x 3oz Beef Patties (£3)<br/>
<p/>
<label>Sauces</label><br/>
<div class="sauces">
Burger <input type="checkbox" id="burgersauce" name="selectedSauces" onclick="calculateTotal()" /><br/>
Dirty Mayo
<input type="checkbox" id="dirtymayo" name="selectedSauces"
onclick="calculateTotal()" /><br/>
Spicy Ketchup
<input type="checkbox" id="spicyketchup" name="selectedSauces"
onclick="calculateTotal()" /><br/>
</div>
<p>
<div id="totalPrice"></div>
</p>
</fieldset>
</form>
</section>
</section>
You're trying to access value on input elements but that doesn't exist as it's attribute in your HTML. You can just use the id attribute instead since those map with the keys in burger_Sauces object.
Note: you were seeing NaN because .value was returning undefined and a number operation on undefined results in NaN. Also you might want to calculate burger sauces price only when a burger patty is selected. I haven't added that check but just a heads up.
var burger_prices = {};
burger_prices["1x3oz"]=2;
burger_prices["2x3oz"]=3;
function getBurgerSizePrice()
{
var burgerSizePrice=0;
var theForm = document.forms["custom-burger"];
var selectedBurger = theForm.elements["burger-meat"];
for(var i = 0; i < selectedBurger.length; i++)
{
//if the radio button is checked
if(selectedBurger[i].checked)
{
burgerSizePrice = burger_prices[selectedBurger[i].value];
break;
}
}
return burgerSizePrice;
}
var burger_Sauces = {}
burger_Sauces["burgersauce"]=2;
burger_Sauces["dirtymayo"]=2;
burger_Sauces["spicyketchup"]=2;
function getBurgerSaucesPrice() {
var BurgerSaucesPrice = 0;
var theForm = document.forms["custom-burger"];
var selectedSauces = theForm.elements["selectedSauces"];
for (var i = 0; i < selectedSauces.length; i++) {
if(selectedSauces[i].checked){
BurgerSaucesPrice += burger_Sauces[selectedSauces[i].id];
}
}
return BurgerSaucesPrice;
}
function calculateTotal()
{
var burgerPrice = getBurgerSizePrice() + getBurgerSaucesPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Burger £"+burgerPrice;
}
<section class="burgerform">
<form action="" id="custom-burger" onsubmit="return false;">
<fieldset>
<legend>Create your Burger Box!</legend>
<label>Meat</label><p/>
<input type="radio" name="burger-meat" value="1x3oz"
onclick="calculateTotal()" />
1 x 3oz Beef Patty (£2)<br/>
<input type="radio" name="burger-meat" value="2x3oz"
onclick="calculateTotal()" />
2 x 3oz Beef Patties (£3)<br/>
<p/>
<label>Sauces</label><br/>
<div class="sauces">
Burger <input type="checkbox" id="burgersauce" name="selectedSauces" onclick="calculateTotal()" /><br/>
Dirty Mayo
<input type="checkbox" id="dirtymayo" name="selectedSauces"
onclick="calculateTotal()" /><br/>
Spicy Ketchup
<input type="checkbox" id="spicyketchup" name="selectedSauces"
onclick="calculateTotal()" /><br/>
</div>
<p>
<div id="totalPrice"></div>
</p>
</fieldset>
</form>
</section>
</section>
Your code almost worked. Your only problem was this line:
BurgerSaucesPrice += burger_Sauces[selectedSauces[i].value];
You should have typed it:
BurgerSaucesPrice += burger_Sauces[selectedSauces[i].id]; /* use id not value */
You also forgot to assign a value for dirtymayo, so I decided to choose an arbitrary value for it.
burger_Sauces["dirtymayo"]=3;
And lastly, you had a break in the for loop that calculates the Sauce total. That will cause it to stop counting all other selected sauces after it counts the first selected on. So I had to comment that break out.
// break; // you should continue to check for other sauces
My guess is that you copied the logic from the radio button group (which makes sense to exit from for loop once you encountered the first selected option), and then forgot to remove the break from the checkbox group.
var burger_prices = new Array();
burger_prices["1x3oz"]=2;
burger_prices["2x3oz"]=3;
function getBurgerSizePrice()
{
var burgerSizePrice=0;
var theForm = document.forms["custom-burger"];
var selectedBurger = theForm.elements["burger-meat"];
for(var i = 0; i < selectedBurger.length; i++)
{
//if the radio button is checked
if(selectedBurger[i].checked)
{
burgerSizePrice = burger_prices[selectedBurger[i].value];
break;
}
}
return burgerSizePrice;
}
var burger_Sauces = new Array();
burger_Sauces["burgersauce"]=2;
burger_Sauces["spicyketchup"]=2;
burger_Sauces["dirtymayo"]=3;
function getBurgerSaucesPrice() {
var BurgerSaucesPrice = 0;
var theForm = document.forms["custom-burger"];
var selectedSauces = theForm.elements["selectedSauces"];
for (var i = 0; i < selectedSauces.length; i++) {
if(selectedSauces[i].checked){
BurgerSaucesPrice += burger_Sauces[selectedSauces[i].id]; /* use id not value */
// break; // you should continue to check for other sauces
}
}
return BurgerSaucesPrice;
}
function calculateTotal()
{
var burgerPrice = getBurgerSizePrice() + getBurgerSaucesPrice();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For the Burger £"+burgerPrice;
}
<section class="burgerform">
<form action="" id="custom-burger" onsubmit="return false;">
<fieldset>
<legend>Create your Burger Box!</legend>
<label>Meat</label><p/>
<input type="radio" name="burger-meat" value="1x3oz"
onclick="calculateTotal()" />
1 x 3oz Beef Patty (£2)<br/>
<input type="radio" name="burger-meat" value="2x3oz"
onclick="calculateTotal()" />
2 x 3oz Beef Patties (£3)<br/>
<p/>
<label>Sauces</label><br/>
<div class="sauces">
Burger <input type="checkbox" id="burgersauce" name="selectedSauces" onclick="calculateTotal()" /><br/>
Dirty Mayo
<input type="checkbox" id="dirtymayo" name="selectedSauces"
onclick="calculateTotal()" /><br/>
Spicy Ketchup
<input type="checkbox" id="spicyketchup" name="selectedSauces"
onclick="calculateTotal()" /><br/>
</div>
<p>
<div id="totalPrice"></div>
</p>
</fieldset>
</form>
</section>
</section>

User friendly Order Form

Hello I am attempting to create a user friendly application that allows the user to buy pencils, pens, and erasers. A total cost should be displayed.
My code mostly works except for one problem. the numbers that the user inputs in the boxes (how many pens/pencils/erasers they would like to buy) are not being used by the code. if I add a value manually to the code it performs the calculation (<input type="number" value="3" placeholder="# of erasers" min="0" id="numOfErasers">) could somebody please help me with getting the calculation to use user inputted numbers?
here's my code (JavaScript/HTML):
<!DOCTYPE html>
<html>
<head>
<title> Pencils Pens Erasers </title>
<script>
//this is the function that calcultes the cost
function costCalculator () {
var total = penCost + pencilCost + eraserCost;
return total;
}
</script>
</head>
<body>
<form>
<!--this is the order form-->
<br>
<u><b>please indicate how many of each you wish to order:</b></u>
<br><br>
Pens:<input type="number" placeholder="# of pens" min="0" id="numOfPens">
Pencils:<input type="number" placeholder="# of pencils" min="0" id="numOfPencils">
Erasers:<input type="number" placeholder="# of erasers" min="0" id="numOfErasers">
<br><br>
please select which province you are ordering from:<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan </option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select>
</form>
<script>
//these are all my variables
var pens = document.getElementById("numOfPens").value
var pencils = document.getElementById("numOfPencils").value
var erasers = document.getElementById("numOfErasers").value
var penCost = 0.50 * pens
var pencilCost = 0.30 * pencils
var eraserCost = 1.00 * erasers
var province = document.getElementById("whichProvince").value
var totalCost = costCalculator()
//this code adds taxes and discount to the total price based on province
if (province == 1) {
totalCost = (5 / 100) * totalCost + totalCost;
} else if (province == 1 && totalCost>30) {
totalCost = totalCost-5
} else if (province == 2) {
totalCost = (5 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
} else if (province == 3) {
totalCost = (6 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
}
/* function test () {
window.alert(total)
}
*/
function test2 () {
window.alert(totalCost)
}
document.write ("<br>" + " The total cost of your purchase will be: " + "<b>" + totalCost + "</b>" + "<br>")
</script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p><p align=center>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator(); test2();" >
</p>
</body>
</html>
As said in the comments you need to get familiar with events (this is another good resouce). The example below is a minimal working example, you can use that as reference when creating mininal reproducible examples.
The main difference is that it uses a button at the end with onclick attribute calling the costCalculator function.
function costCalculator() {
var pensTotal = document.getElementById("numOfPens").value * 0.5;
var pencilsTotal = document.getElementById("numOfPencils").value * 0.3;
var erasersTotal = document.getElementById("numOfErasers").value;
var total = parseFloat(pensTotal + pencilsTotal + erasersTotal);
var province = document.getElementById("whichProvince").value;
if (province == 1) {
total = (5 / 100) * total + total;
if (total > 30) {
total -= 5;
}
} else if (province == 2) {
total = (5 / 100) * total + total;
total += 2;
} else if (province == 3) {
total = (6 / 100) * total + total;
total += 2;
}
document.getElementById("output").innerHTML = total;
}
<label for="numOfPens">Pens:</label>
<input type="number" placeholder="# of pens" min="0" id="numOfPens"><br/>
<label for="numOfPencils">Pencils:</label>
<input type="number" placeholder="# of pencils" min="0" id="numOfPencils"><br/>
<label for="numOfErasers">Erasers:</label>
<input type="number" placeholder="# of erasers" min="0" id="numOfErasers"><br/>
<label for="whichProvince">please select which province you are ordering from:</label>
<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan</option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select><br/>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator()">
<p id="output"></p>
I've done a few irrelevant changes to your code, I'll answer anything you need in the comments.

if statement not returning a value

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>

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>

Categories

Resources