JavaScript Total Price List Not Displaying - javascript

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>

Related

Javascript calculation resulting NaN

I have a form to calculate the total value from a form but it results in a nan error even though the values of the html inputs is numerical. What am I doing wrong?
function myFunction() {
var y = document.getElementsByName("optradio").value;
var z = document.getElementsByName("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
You must cycle through the radios to get the value. getElementsByName returns multiple elements.
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function valueOfRadio(name) {
// Get all of the radios by name
var radios = document.getElementsByName(name);
// Go through each one
for (var i = 0, length = radios.length; i < length; i++) {
// If it's checked, lets return it's value
if (radios[i].checked) {
return radios[i].value;
}
}
}
function myFunction() {
// Go get the right radio value
var y = valueOfRadio('optradio');
// Same problem here. Multiple returned, but we know we only have one element so we index to 0.
//You could alternatively use getElementsById for this which will return a single node.
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
getElementsByName returns an array and you have to test all the radios to see if they are checked.
Try it:
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label><label class="radio-inline"><input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function myFunction() {
var radios = document.getElementsByName("optradio");
var y = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
y += +radios[i].value;
}
}
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>
Actually getElementsByName returns array of elements with the name given, name optradio is allocated for 2 radio buttons, so you need to do like this
function myFunction() {
var radioarray = document.getElementsByName("optradio");
var y;
for (var i = 0; i < radioarray.length; i++) {
if (radioarray[i].checked) {
y = radioarray[i].value;
}
}
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Here is an example using a select instead of radio buttons, and it looks a little more compact and clean. I also used jQUery instead of plain Javascript because the code is a lot cleaner.
function myFunction() {
var result = parseInt($("[name=optradio]").val()) + parseInt($("[name=extra-hours]").val());
$("#result").text(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="optradio">
<option value="25">Half day (3hrs)
<option value="50">Full day (6hrs)
</select>
<input type="number" value="0" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
document.getElementsByName("...")
returns a node list, not an individual node. You should use an id to select just a single node (preferred). That is
var y = document.getElementById("optradio").value
var z = document.getElementById("extra-hours").value
The properties "name" and "id" have different meanings, so make sure you use the one you actually mean.
If you want a unique identifier, use "id", if you want to group a selection of your DOM elements, use "name".
Additionally, the value for the radio button is always the same, you need to apply it conditionally based on the 'selected' property.
function myFunction() {
var half = document.getElementById("half");
var full = document.getElementById("full");
var y = half.checked ? half.value : full.value;
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" id="half" value="25" checked>Half day (3hrs)
<input type="radio" name="optradio" id="full" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Finally, although I'm not going to show it, you're probably best learning jQuery now; everything else uses jQuery. Everyone uses jQuery because it's better than base javascript. As Christian Juth showed in his answer, you probably want to make it a selection box, too.

How to add totals up and display them in a text box

When trying to get my total to pop up, I can't seem to get it. Above this code in my .js file is the toggle check boxes; all of it works as of right now, but adding them together and coming up with a total in the txtTotal box is the only thing I'm struggling with.
var total;
var outputArea;
var btnCompute;
function ToggleBurgers() {
var checkbox = document.getElementById('chkBurgers');
var burgers = document.getElementById('divBurgers');
if (checkbox.checked) {
burgers.style.visibility = 'visible';
} else {
burgers.style.visibility = 'hidden';
}
}
function ToggleFries(){
var checkbox = document.getElementById('chkFries');
var fries = document.getElementById('divFries');
if (checkbox.checked) {
fries.style.visibility = 'visible';
} else {
fries.style.visibility = 'hidden';
}
}
function ToggleDrinks(){
var checkbox = document.getElementById('chkDrinks')
var drinks = document.getElementById('divDrinks');
if (checkbox.checked) {
drinks.style.visibility = 'visible';
}else {
drinks.style.visibility = 'hidden';
}
}
function ComputeTotal() {
var total = 0;
var burgers = document.getElementById('divBurgers');
var fries = document.getElementById('divFries');
var drinks = document.getElementById('divDrinks');
var radBurgerRegular = document.getElementById('radBurgerRegular');
var radBurgerCheese = document.getElementById('radBurgerCheese');
var radBurgerBacon = document.getElementById('radBurgerBacon');
var radBurgerBaconCheese = document.getElementById('radBurgerBaconCheese');
var radFriesSmall = document.getElementById('radFriesSmall');
var radFriesMedium = document.getElementById('radFriesMedium');
var radFriesLarge = document.getElementById('radFriesLarge');
var radDrinkSoda = document.getElementById('radDrinkSoda');
var radDrinkWater = document.getElementById('radDrinkWater');
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total + divBurgers + divFries + divDrinks;
if (burgers.checked){
if (radBurgerRegular.checked){
total = total + radBurgerRegular;
}if (radBurgerCheese.checked){
total = total + radBurgerCheese;
}if (radBurgerBacon.checked){
total = total + radBurgerBacon;
}if (radBurgerBaconCheese.checked){
total = total + radBurgerBaconCheese;
}
}else if (fries.checked){
if (radFriesSmall.checked){
total = total + radFriesSmall;
}if (radFriesMedium.checked){
total = total + radFriesMedium;
}if (radFriesSmall.checked){
total = total + radFriesLarge;
}
} else if (drinks.checked){
if (radDrinkSoda.checked){
total = total + radDrinkSoda;
}if (radDrinkWater.checked){
total = total + radDrinkWater;
}
}
}
function init() {
var chkBurgers = document.getElementById('chkBurgers');
chkBurgers.onchange = ToggleBurgers;
var chkFries = document.getElementById('chkFries');
chkFries.onchange = ToggleFries;
var chkDrinks = document.getElementById('chkDrinks');
chkDrinks.onchange = ToggleDrinks;
var btnCompute = document.getElementById('btnCompute');
btnCompute.onclick = ComputeTotal;
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total
}
window.onload = init;
HTML code is here
<!DOCTYPE html>
<html>
<head>
<title>Restaurant Menu</title>
</head>
<body>
<div class="page">
<div class="topbar">
Menu
</div>
<div class="row">
<!--Burgers CheckBox-->
<div class="cell">
<input type="checkbox" name="chkBurgers" id="chkBurgers" /> <label for="chkBurgers">Burgers</label>
</div>
<!--Cell Containing Burger Menu-->
<div class="cell" id="divBurgers" style="visibility:hidden;">
<input type="radio" name="radBurgers" id="radBurgerRegular" /><label for="radBurgerRegular">Regular (4.19)</label><br />
<input type="radio" name="radBurgers" id="radBurgerCheese" /><label for="radBurgerCheese">w/ Cheese (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBacon" /><label for="radBurgerBacon">w/ Bacon (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBaconCheese" /><label for="radBurgerBaconCheese">w/ Bacon and Cheese (5.39)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Fries CheckBox-->
<div class="cell">
<input type="checkbox" name="chkFries" id="chkFries" /><label for="chkFries">Fries</label>
</div>
<!--Cell Containing Fries Menu-->
<div class="cell" id="divFries" style="visibility:hidden;">
<input type="radio" name="radFries" id="radFriesSmall" /><label for="radFriesSmall">Small (2.39)</label><br />
<input type="radio" name="radFries" id="radFriesMedium" /><label for="radFriesMedium">Medium (3.09)</label><br />
<input type="radio" name="radFries" id="radFriesLarge" /><label for="radFriesSmall">Large (4.99)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Drinks CheckBox-->
<div class="cell">
<input type="checkbox" name="chkDrinks" id="chkDrinks" /><label for="chkDrinks">Drinks</label>
</div>
<!--Cell Containing Drink Menu-->
<div class="cell" id="divDrinks" style="visibility:hidden;">
<input type="radio" name="radDrinks" id="radDrinkSoda" /><label for="radDrinkSoda">Soda (1.69)</label><br />
<input type="radio" name="radDrinks" id="radDrinkWater" /><label for="radDrinkWater">Bottled Water (1.49)</label><br />
</div>
<!--Cell Containing Compute Button and Total Field-->
<div class="cell" style="float:right;">
Total Meal Cost: <input type="text" name="txtTotal" id="txtTotal" /><br /><br />
<button id="btnCompute" name="btnCompute">Compute Total</button>
</div>
</div>
<div class="clear"></div>
</div>
<link rel="stylesheet" type="text/css" href="Chapter9.css">
<script src="Chapter9.js"></script>
</body>
</html>
first off, you want to get rid of the else's in the block where you are checking if things are checked. that only allows you to get Burger or Fries or Drink, when you want to be able to get one of each.
so that should be:
if(burgers.checked){
if(radBurgerRegular.checked){
total = total + radBurgerRegular;
}
...
}
if(fries.checked){
...
}
if(drinks.checked){
...
}
Additionally, you are doing all of this adding to total, and then not doing anything with it.
Move this:
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total + divBurgers + divFries + divDrinks;
to the bottom of the function (and get rid of all the divBurgers, divFries stuff):
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total;
The next problem is that nowhere is the price actually being added. When you getElementById(), that value does not magically become the price that is in parenthesis. You need to replace total = total + radBurgerRegular with the price:
if(burgers.checked){
if(radBurgerRegular.checked){
total = total + 4.19;
}
...
}
lastly, you want to change the display area to a span instead of an input. change:
Total Meal Cost: <input type="text" name="txtTotal" id="txtTotal" />
to:
Total Meal Cost: <span id="txtTotal"></span>
and that should do it!
EDIT:
last thing, you need to change the following lines:
var burgers = document.getElementById('divBurgers');
var fries = document.getElementById('divFries');
var drinks = document.getElementById('divDrinks');
to this:
var burgers = document.getElementById('chkBurgers');
var fries = document.getElementById('chkFries');
var drinks = document.getElementById('chkDrinks');
because a div cannot be "checked" and will always return undefined (false).
Total is undefined in init.
Replace
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total
with
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = 0;
Or possibly a better option is to initialize total.
total = 0;
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total;
The problem is inside the function ComputeTotal.
I propose you to take a look to the following implementation:
var total;
var outputArea;
var btnCompute;
function ToggleBurgers() {
var checkbox = document.getElementById('chkBurgers');
var burgers = document.getElementById('divBurgers');
if (checkbox.checked) {
burgers.style.visibility = 'visible';
} else {
burgers.style.visibility = 'hidden';
}
}
function ToggleFries(){
var checkbox = document.getElementById('chkFries');
var fries = document.getElementById('divFries');
if (checkbox.checked) {
fries.style.visibility = 'visible';
} else {
fries.style.visibility = 'hidden';
}
}
function ToggleDrinks(){
var checkbox = document.getElementById('chkDrinks')
var drinks = document.getElementById('divDrinks');
if (checkbox.checked) {
drinks.style.visibility = 'visible';
}else {
drinks.style.visibility = 'hidden';
}
}
function ComputeTotal() {
var total = 0;
var burgersCost = 0;
var friesCost = 0;
var drinksCost = 0;
if (document.getElementById('chkBurgers').checked) {
var burgersObj = document.querySelector('input[name="radBurgers"]:checked');
var burgersValFromLabel = document.querySelector('label[for="' + burgersObj.id + '"]').textContent;
burgersCost = burgersValFromLabel.substring(burgersValFromLabel.lastIndexOf("(")+1,burgersValFromLabel.lastIndexOf(")"));
}
if (document.getElementById('chkFries').checked) {
var friesObj = document.querySelector('input[name="radFries"]:checked');
var friesValFromLabel = document.querySelector('label[for="' + friesObj.id + '"]').textContent;
friesCost = friesValFromLabel.substring(friesValFromLabel.lastIndexOf("(") + 1, friesValFromLabel.lastIndexOf(")"));
}
if (document.getElementById('chkDrinks').checked) {
var drinksObj = document.querySelector('input[name="radDrinks"]:checked');
var drinksValFromLabel = document.querySelector('label[for="' + drinksObj.id + '"]').textContent;
drinksCost = drinksValFromLabel.substring(drinksValFromLabel.lastIndexOf("(") + 1, drinksValFromLabel.lastIndexOf(")"));
}
var outputArea = document.getElementById('txtTotal');
outputArea.value = total + parseFloat(burgersCost) + parseFloat(friesCost) + parseFloat(drinksCost);
}
function init() {
var chkBurgers = document.getElementById('chkBurgers');
chkBurgers.onchange = ToggleBurgers;
var chkFries = document.getElementById('chkFries');
chkFries.onchange = ToggleFries;
var chkDrinks = document.getElementById('chkDrinks');
chkDrinks.onchange = ToggleDrinks;
var btnCompute = document.getElementById('btnCompute');
btnCompute.onclick = ComputeTotal;
var outputArea = document.getElementById('txtTotal');
outputArea.innerHTML = total
}
window.onload = init;
<div class="page">
<div class="topbar">
Menu
</div>
<div class="row">
<!--Burgers CheckBox-->
<div class="cell">
<input type="checkbox" name="chkBurgers" id="chkBurgers" /> <label for="chkBurgers">Burgers</label>
</div>
<!--Cell Containing Burger Menu-->
<div class="cell" id="divBurgers" style="visibility:hidden;">
<input type="radio" name="radBurgers" id="radBurgerRegular" /><label for="radBurgerRegular">Regular (4.19)</label><br />
<input type="radio" name="radBurgers" id="radBurgerCheese" /><label for="radBurgerCheese">w/ Cheese (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBacon" /><label for="radBurgerBacon">w/ Bacon (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBaconCheese" /><label for="radBurgerBaconCheese">w/ Bacon and Cheese (5.39)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Fries CheckBox-->
<div class="cell">
<input type="checkbox" name="chkFries" id="chkFries" /><label for="chkFries">Fries</label>
</div>
<!--Cell Containing Fries Menu-->
<div class="cell" id="divFries" style="visibility:hidden;">
<input type="radio" name="radFries" id="radFriesSmall" /><label for="radFriesSmall">Small (2.39)</label><br />
<input type="radio" name="radFries" id="radFriesMedium" /><label for="radFriesMedium">Medium (3.09)</label><br />
<input type="radio" name="radFries" id="radFriesLarge" /><label for="radFriesSmall">Large (4.99)</label><br />
</div>
</div>
<div class="clear"></div>
<div class="row">
<!--Drinks CheckBox-->
<div class="cell">
<input type="checkbox" name="chkDrinks" id="chkDrinks" /><label for="chkDrinks">Drinks</label>
</div>
<!--Cell Containing Drink Menu-->
<div class="cell" id="divDrinks" style="visibility:hidden;">
<input type="radio" name="radDrinks" id="radDrinkSoda" /><label for="radDrinkSoda">Soda (1.69)</label><br />
<input type="radio" name="radDrinks" id="radDrinkWater" /><label for="radDrinkWater">Bottled Water (1.49)</label><br />
</div>
<!--Cell Containing Compute Button and Total Field-->
<div class="cell" style="float:right;">
Total Meal Cost: <input type="text" name="txtTotal" id="txtTotal" /><br /><br />
<button id="btnCompute" name="btnCompute">Compute Total</button>
</div>
</div>
<div class="clear"></div>
</div>

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;
}
}

Javascript form NAN error

Firstly I apologies, I've just starting out with JavaScript
I have a problem with a form. I have two groups of Radio buttons on the form (age and bmi)
Everytime the 'Calculate' button is clicked, I want add the values of each checked Radio button and alert this to the screen.
It works in Chrome, but ALL other browsers give an NAN error.
Can anyone help?
<br>
<input type="radio" name="age" class="myradioButton" value = "1"/>
<input type="radio" name="bmi" class="myradioButton" value = "3"/>
<input type="button" name="Calculate" id="calculate"onclick="calculatehealth()" value="Calculate"/>
<br>
<script>
function calculatehealth() {
var valueAge = document.forms['myForm'].elements["age"].value;
var valueint = parseInt(valueAge);
var valueBmi = document.forms['myForm'].elements["bmi"].value;
var Bmiint = parseInt(valueBmi);
var total = Bmiint + valueint;
alert(total);
}
Demo: http://jsfiddle.net/z4RKx/
HTML
<form id="myForm">
<input type="radio" name="age" class="myradioButton" value="1" />
<input type="radio" name="bmi" class="myradioButton" value="3" />
<input type="button" name="Calculate" value="Calculate" onclick='calculatehealth()' />
</form>
JS
function calculatehealth() {
var valueint = 0;
if (document.forms['myForm'].elements["age"].checked) {
valueint += parseInt(document.forms['myForm'].elements["age"].value);
}
if (document.forms['myForm'].elements["bmi"].checked) {
valueint += parseInt(document.forms['myForm'].elements["bmi"].value);
}
alert(valueint);
}
And if you have many elements this might be a good alternative:
function calculatehealth() {
var valueint = 0;
for(i = 0; i < document.forms['myForm'].elements.length; i++) {
if (document.forms['myForm'].elements[i].checked) {
valueint += parseInt(document.forms['myForm'].elements[i].value);
}
}
alert(valueint);
}

Adding form verification in this case

I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail

Categories

Resources