how to show the output after the form submit in JavaScript - 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>

Related

At least one radio and checkbox must be select in JavaScript

how to validate all the section by at least choose one option. with my code, it just show the first "please select 1". so how to edit the code to show the all requirement like "pls choose at least one" at beside the section or below the submit button. I'm just a beginner, now learning for JavaScript. You are prefer to done with some code editor, to have a better understand for beginner. Here is my code :
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*454.58;
elec["elec2"] = 200*454.58;
elec["elec3"] = 300*454.58;
elec["elec4"] = 400*454.58;
elec["elec5"] = 500*454.58;
elec["elec6"] = 600*454.58;
elec["elec7"] = 700*454.58;
elec["elec8"] = 800*454.58;
elec["elec9"] = 900*454.58;
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 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('input[type="checkbox"]');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco;
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vpeople()
{
var cp = document.getElementsByName('selectedperson');
for (var i = 0; i < cp.length; i++)
{
if (cp[i].type == 'radio')
{
if (cp[i].checked) {return true}
}
}
return false;
}
function velec()
{
var ce = document.getElementsByName('electricity');
for (var i = 0; i < ce.length; i++)
{
if (ce[i].type == 'radio')
{
if (ce[i].checked) {return true}
}
}
return false;
}
function vrcyalu()
{
var crcyalu = document.getElementsByName('yesalu');
for (var i = 0; i < crcyalu.length; i++)
{
if (crcyalu[i].type == 'checkbox')
{
if (crcyalu[i].checked) {return true}
}
}
return false;
}
function vrcyplas()
{
var crcyplas = document.getElementsByName('yesalu');
for (var i = 0; i < crcyplas.length; i++)
{
if (crcyplas[i].type == 'checkbox')
{
if (crcyplas[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
if(!vpeople())
{
alert("Please select1");
return false;
}
return true;
if(!vwaste())
{
alert("Please select2");
return false;
}
return true;
if(!velec())
{
alert("Please select3");
return false;
}
return true;
if(!vrcyalu())
{
alert("Please select4");
return false;
}
return true;
if(!vrcyplas())
{
alert("Please select5");
return false;
}
return true;
checkAllRecycles;
}
<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/><br/>
<label><i class="fa fa-flash"></i>Energy Consumption Per Month</label>
<br/>
<label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0</option>
<option value="elec1">100</option>
<option value="elec2">200</option>
<option value="elec3">300</option>
<option value="elec4">400</option>
<option value="elec5">500</option>
<option value="elec6">600</option>
<option value="elec7">700</option>
<option value="elec8">800</option>
<option value="elec9">900</option>
</select>
<br/><br/>
<label><i class="fa fa-flash"></i>Recycle </label>
<br/>
<label for='yesalu' class="alu">&nbspAluminium and Steel&nbsp&nbsp</label>
<input type="checkbox" id="yesalu" name='yesalu' 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' 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>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
thx you very much for helping me, stay safe.
hello please check this page :
https://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript

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>

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>

getting Numerical Value from Radio button using JavaScript code

Why this code is not returning the value.When I click Calculate, it does not work.
Comparison is ==
Assignment is =.
You need ageNumerical = 0;
Check out this fiddle.
Here is the snippet.
function getValue() {
var a = patientAge();
var b = patientBmi();
var c = history();
var d = patientDiet();
var totalValue;
totalValue = a + b + c + d;
document.getElementById('message').innerHTML = totalValue;
}
function patientAge() {
var age = document.getElementsByName('ageRange');
var ageBracket;
var ageNumerical;
for (var i = 0; i < age.length; i++) {
if (age[i].checked) {
ageBracket = age[i].value;
}
}
if (ageBracket == "1-25") {
ageNumerical = 0;
} else if (ageBracket == "26-40") {
ageNumerical = 5;
} else if (ageBracket == "41-60") {
ageNumerical = 8;
} else {
ageNumerical = 10;
}
return ageNumerical;
}
function patientBmi() {
var bmi = document.getElementsByName('bmiRange');
var bmiValue;
var bmiNumerical;
for (var i = 0; i < bmi.length; i++) {
if (bmi[i].checked) {
bmiValue = bmi[i].value;
}
}
if (bmiValue == "0-25") {
bmiNumerical = 0;
} else if (bmiValue == "26-30") {
bmiNumerical = 0;
} else if (bmiValue == "31-35") {
bmiNumerical = 9;
} else {
bmiNumerical = 10;
}
return bmiNumerical;
}
function history() {
var patientHistory = document.getElementsByName('familyHistory');
var historyAnswer;
var historyNumerical;
for (var i = 0; i < patientHistory.length; i++) {
if (patientHistory[i].checked) {
historyAnswer = patientHistory[i].value;
}
}
if (historyAnswer == "No") {
historyNumerical = 0;
} else if (historyAnswer == "Grandparent") {
historyNumerical = 7;
} else if (historyAnswer == "Sibling") {
historyNumerical = 15;
} else {
historyNumerical = 15;
}
return historyNumerical;
}
function patientDiet() {
var dietQuestion = document.getElementsByName('dietHabits');
var dietAnswer;
var dietNumerical;
for (var i = 0; i < dietQuestion.length; i++) {
if (dietQuestion[i].checked) {
dietAnswer = dietQuestion[i].value;
}
}
if (dietAnswer == "Low sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Normal sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Quite high sugar") {
dietNumerical = 7;
} else {
dietNumerical = 10;
}
return dietNumerical;
}
<div id="ageQuestion">
<p>How old are you?</p>
<label for="age1">1-25</label>
<input type="radio" name="ageRange" value="1-25" />
<label for="age2">26-40</label>
<input type="radio" name="ageRange" value="26-40" />
<label for="age3">41-60</label>
<input type="radio" name="ageRange" value="41-60" />
<label for="age4">60+</label>
<input type="radio" name="ageRange" value="60+" />
</div>
<div id="bmi">
<p>What is your BMI?</p>
<label for="bmiLevel">0-25</label>
<input type="radio" name="bmiRange" value="0-25" />
<label for="bmiLevel">26-30</label>
<input type="radio" name="bmiRange" value="26-30" />
<label for="bmiLevel">31-35</label>
<input type="radio" name="bmiRange" value="31-35" />
<label for="bmiLevel">35+</label>
<input type="radio" name="bmiRange" value="35+" />
</div>
<div id="family">
<p>Does anybody in your family have Diabetes?</p>
<label for="history">No</label>
<input type="radio" name="familyHistory" value="No" />
<label for="history">Grandparent</label>
<input type="radio" name="familyHistory" value="Grandparent" />
<label for="history">Sibling</label>
<input type="radio" name="familyHistory" value="Sibling" />
<label for="history">Parent</label>
<input type="radio" name="familyHistory" value="Parent" />
</div>
<div id="diet">
<p>How would you describe your diet?</p>
<label for="diet">Low sugar</label>
<input type="radio" name="dietHabits" value="Low sugar" />
<label for="diet">Normal sugar</label>
<input type="radio" name="dietHabits" value="Normal sugar" />
<label for="diet">Quite high sugar</label>
<input type="radio" name="dietHabits" value="Quite high sugar" />
<label for="diet">High sugar</label>
<input type="radio" name="dietHabits" value="High sugar" />
</div>
<button onclick="getValue()">Calculate</button>
<p id="message"></p>
Change == to = when assigning values.
ageNumerical == 0;
to
ageNumerical = 0;

Basic Calculations using Javascript for Holiday Booking System

********************************** EDIT *********************************
HERE IS LINK TO JSFIDDLE TO MAKE IT EASIER TO ANALYSE WHAT I'M TRYING TO RESOLVE
http://jsfiddle.net/Kaleidoscar/ZEd5V/
I have a college assignment to complete which requires me to calculate the price of a hotel and multiply it by the number of days plus any extras to be added to the price of the hotel.
Unfortunately, the code I've provided doesn't work and I'm not sure how I can multiply the hotel price with the holiday duration... If anyone can help me with this problem, I would gladly appreciate the help.
Here is the html code for my assignment:
HTML
Hotels
<div class ="HotelBooking">
<form id="getHotelBooking" onsubmit="return false;">
<ul>
<li><input type="radio" id="Miramar" name="selectedhotel" value="Hotel Miramar" /> Hotel Miramar</li>
<li><input type="radio" id="Jazminas" name="selectedhotel" value="Las Jazminas" /> Las Jazminas</li>
<li><input type="radio" id="Tropicana" name="selectedhotel" value="Tropicana Gardens" /> Tropicana Gardens</li>
</ul>
<input type="button" value="OK" class="buttonstyle" onclick="testHotelImages()" />
<!--INFORMATION ICONS -->
<div class="informationWrap">
<img src="images/information_italic.png" alt="info" class ="infoIcon" />
<p class="imgDescription">Please choose from the selection of Hotels provided. Only 1 hotel can be purchased per hotel booking. To the left hand-side, a hotel description will appear. Only press the OK command once you have confirmed your hotel stay.</p>
</div>
<img id="PricePlaceHolder" src="images/PricePlaceHolder.jpg" alt="Image gallery" height="150" width="150" />
<div class ="Images">
<img id="Hotelplaceholder" src="images/Hotelplaceholder.jpg" alt="Image gallery" height="300" width="615" />
</div>
</form>
</div>
Options
<div class ="HotelBooking">
<form id="getOptionsBooking" onsubmit="return false;">
<ul>
<li><input type="checkbox" id="local" name="check" value="LocalTourOption" /> Tours to Local Interests</li>
<li><input type="checkbox" id="flyDrive" name="check" value="FlyDriveOption" /> Fly-Drive (have a rental car waiting at the airport)</li>
<li><input type="checkbox" id="balcony" name="check" value="BalconyOption" /> Balcony</li>
</ul>
<p><input type="button" class="buttonstyle" value="OK" onclick="ExtraInterest()" /></p>
Duration
<form id="FormNights" action="#">
<p><label for="Nights">Nights:</label>;
<input type="text" size="10" id="Nights" /> </p>
Your Party
<form id="Party" action="#">
<p><label for="Adults">Adults:</label>
<input type="text" size="2" id="AdultsParty" /> </p>
<p><input type="button" class="buttonstyle" value="OK" onclick="PartyDetails()" /></p>
</form>
<h3>Your Holiday Summary</h3>
<div id="TotalCost"> </div>
JAVASCRIPT
var hotel_prices = new Array();
hotel_prices["Hotel Miramar"] = 50;
hotel_prices["Las Jazminas"] = 75;
hotel_prices["Tropicana Gardens"] = 100;
function getHotelPrice() {
var HotelSizePrice = 0;
var theForm = document.forms["getHotelBooking"];
var selectedHotel = theForm.elements["selectedhotel"];
for (var i = 0; i < selectedHotel.length; i++) {
if (selectedHotel[i].checked) {
HotelSizePrice = hotel_prices[selectedHotel[i].value];
break;
}
}
return HotelSizePrice;
function LocalExtra() {
var LocalPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeLocal = theForm.elements["local"];
if (includeLocal.checked == true) {
LocalPrice = 60;
}
return LocalPrice;
}
function FlyDriveExtra() {
var FlyDrivePrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeFlyDrive = theForm.elements["flyDrive"];
if (includeFlyDrive.checked == true) {
FlyDrivePrice = 45;
}
return FlyDrivePrice;
}
function BalconyExtra() {
var BalconyPrice = 0;
var theForm = document.forms["getOptionsBooking"];
var includeBalcony = theForm.elements["balcony"];
if (includeBalcony.checked == true) {
BalconyPrice = 30;
}
return BalconyPrice;
}
function getNights() {
var theForm = document.forms["FormNights"];
var quantity = theForm.elements["Nights"];
var duration = 0;
if (quantity.value != "") {
duration = parseInt(quantity.value);
}
return duration;
}
function getAdults() {
var theForm = document.forms["Party"];
var quantity = theForm.elements["AdultsParty"];
var howmany = 0;
if (quantity.value != "") {
howmany = parseInt(quantity.value);
}
return howmany;
}
function getTotal() {
var HotelPrice = getHotelPrice() + LocalExtra() + FlyDriveExtra() + BalconyExtra() + getNights() + getAdults();
document.getElementById('TotalCost').innerHTML =
"Total Price For Hotel £" + HotelPrice;
}
}

Categories

Resources