********************************** 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;
}
}
Related
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>
I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}
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>
I got the following Javascript code that works properly in Mozilla Firefox but it doesn't in Google Chrome. Any ideea why it will do that?
totalBMI in Chrome even if the value is 45(checking all the last buttons will give you the value 45 which is bigger then 26 so the result should be setting the hRisk div to display:-inline instead of display:none, as the function changeCss() does.) it still consider it to be 0, cause it displays the low risk message. In Firefox, it always displays the right answer.
Javascript code :
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
}
changeCSS();
} else if (totalBMI > 16 ) {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
}
changeCSS();
} else {
function changeCSS() {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
changeCSS();
}
}
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
HTML code:
<script src="jsbmi4.js"></script>
<title>Java</title>
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"> <span class="span1"> How old are you? </span>
<input type="radio" id="age1" name="age" value="0">0-25
<input type="radio" id="age1" name="age" value="5">26-40
<input type="radio" id="age1" name="age" value="8">41-60
<input type="radio" id="age1" name="age" value="10">60+
</label>
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span>
<input type="radio" id="bmi1" name="bmi" value="0">0-25
<input type="radio" id="bmi1" name="bmi" value="0">26-30
<input type="radio" id="bmi1" name="bmi" value="9">31-35
<input type="radio" id="bmi1" name="bmi" value="10">35+
</label>
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes? </span>
<input type="radio" id="fam1" name="fam" value="0">No
<input type="radio" id="fam1" name="fam" value="7">Grandparent
<input type="radio" id="fam1" name="fam" value="15">Sibling
<input type="radio" id="fam1" name="fam" value="15">Parent
</label>
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span>
<input type="radio" id="diet1" name="diet" value="0">Low sugar
<input type="radio" id="diet1" name="diet" value="0">Normal sugar
<input type="radio" id="diet1" name="diet" value="7">Quite high sugar
<input type="radio" id="diet1" name="diet" value="10">High sugar
</label>
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()">
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
Only modification that I had to do is delete the function changeCSS() and just add what was inside in the if statement.
Thanks Fuximus Foe.
JSCode is here.
function getAgeValue()
{
for (var i = 0; i < document.getElementsByName('age').length; i++)
{
if (document.getElementsByName('age')[i].checked)
{
return document.getElementsByName('age')[i].value;
}
}
}
function getBmiValue()
{
for (var i = 0; i < document.getElementsByName('bmi').length; i++)
{
if (document.getElementsByName('bmi')[i].checked)
{
return document.getElementsByName('bmi')[i].value;
}
}
}
function getFamValue()
{
for (var i = 0; i < document.getElementsByName('fam').length; i++)
{
if (document.getElementsByName('fam')[i].checked)
{
return document.getElementsByName('fam')[i].value;
}
}
}
function getDietValue()
{
for (var i = 0; i < document.getElementsByName('diet').length; i++)
{
if (document.getElementsByName('diet')[i].checked)
{
return document.getElementsByName('diet')[i].value;
}
}
}
function CalculateValue() {
var age = +getAgeValue('age'),
bmi = +getBmiValue('bmi'),
fami = +getFamValue('fam'),
diet = +getDietValue('diet'),
totalBMI = age + bmi + fami + diet;
totalBMI = parseFloat(totalBMI);
alert(totalBMI);
if (totalBMI > 26) {
document.getElementById("btn").onclick = function() {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'inline';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
}
} else if (totalBMI > 16 ) {
document.getElementById("btn").onclick = function() {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'inline';
}
} else {
document.getElementById("btn").onclick = function() {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'inline';
}
}
}
You have not closed any input tags consider using <input ... /> self closing tags. You have misplaced closing </label> tags.
You shouldn't redeclare a function just to use on the next line.
Not sure, why you're binding to onclick event when you already have the answer, that makes it work only when the user hits the calculate button twice.
After fiddling around with this, removing the the changeCSS functions and just executing their code straight away fixes the problem. This is because in Chrome is grabbing the first definition of the function regardless whether the cursor reaches it or not, thus executing only the first changeCSS function on all three cases; firefox reads the correct definition.
JAVASCRIPT:
function CalculateValue() {
var totalBMI = 0+parseInt(getAgeValue('age'))
+parseInt(getBmiValue('bmi'))
+parseInt(getFamValue('fam'))
+parseInt(getDietValue('diet'));
alert(totalBMI);
if (totalBMI > 26) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var hMessage = document.getElementById("hRisk");
hMessage.style.display = 'block';
/*var newSpan = document.createElement("span");
var newSpanText = document.createTextNode("Your main factors risk are " );
newSpan.appendChild(newSpanText);
var pElem = document.getElementById("space");
pElem.appendChild(newSpan); */
//}
//}
//changeCSS();
} else if (totalBMI > 16) {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var mMessage = document.getElementById("mRisk");
mMessage.style.display = 'block';
//}
//}
//changeCSS();
} else {
//function changeCSS(){
//document.getElementById("btn").onclick = function () {
var lMessage = document.getElementById("lRisk");
lMessage.style.display = 'block';
//}
//}
//changeCSS();
}
}
function getAgeValue() {
for (var i = 0; i < document.getElementsByName('age').length; i++) {
if (document.getElementsByName('age')[i].checked) {
return document.getElementsByName('age')[i].value;
}
}
return 0;
}
function getBmiValue() {
for (var i = 0; i < document.getElementsByName('bmi').length; i++) {
if (document.getElementsByName('bmi')[i].checked) {
return document.getElementsByName('bmi')[i].value;
}
}
return 0;
}
function getFamValue() {
for (var i = 0; i < document.getElementsByName('fam').length; i++) {
if (document.getElementsByName('fam')[i].checked) {
return document.getElementsByName('fam')[i].value;
}
}
return 0;
}
function getDietValue() {
for (var i = 0; i < document.getElementsByName('diet').length; i++) {
if (document.getElementsByName('diet')[i].checked) {
return document.getElementsByName('diet')[i].value;
}
}
return 0;
}
HTML:
<body>
<form method="post" action="process.php" id="radioForm">
<fieldset>
<div>
<label for="age" class="lClass"><span class="span1"> How old are you?</span></label>
<input type="radio" id="age1" name="age" value="0"/>0-25
<input type="radio" id="age1" name="age" value="5"/>26-40
<input type="radio" id="age1" name="age" value="8"/>41-60
<input type="radio" id="age1" name="age" value="10"/>60+
</div>
<div>
<label for="bmi"> <span class="span1"> What is your BMI? </span></label>
<input type="radio" id="bmi1" name="bmi" value="0"/>0-25
<input type="radio" id="bmi1" name="bmi" value="0"/>26-30
<input type="radio" id="bmi1" name="bmi" value="9"/>31-35
<input type="radio" id="bmi1" name="bmi" value="10"/>35+
</div>
<div>
<label for="fam"> <span class="span1"> Does anybody in your family have diabetes?</span></label>
<input type="radio" id="fam1" name="fam" value="0"/>No
<input type="radio" id="fam1" name="fam" value="7"/>Grandparent
<input type="radio" id="fam1" name="fam" value="15"/>Sibling
<input type="radio" id="fam1" name="fam" value="15"/>Parent
</div>
<div>
<label for="diet"> <span class="span1"> How would you describe your diet? </span></label>
<input type="radio" id="diet1" name="diet" value="0"/>Low sugar
<input type="radio" id="diet1" name="diet" value="0"/>Normal sugar
<input type="radio" id="diet1" name="diet" value="7"/>Quite high sugar
<input type="radio" id="diet1" name="diet" value="10"/>High sugar
</div>
<div class="button">
<input id="btn" type="button" value="Calculate" onclick="CalculateValue()"/>
<!-- <input id="submit" type"submit" value="submit"> -->
</div>
</fieldset>
</form>
<div id="lRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healty lifestyle in terms of diet and exercise. </p>
</div>
<div id="mRisk" style="display:none;">
<h2> Your Result </h2>
<p> Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at http://www.zha.org.zd. </p>
</div>
<div id="hRisk" style="display:none;">
<h2> Your Result </h2>
<p>Your results show that you currently have a HIGH risk of developing diabetes.<span id="space"></span> We advice that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </p>
</div>
</body>
and the JSFiddle: http://jsfiddle.net/kWyx8/
<div class="content" data-category="shoes" data-price="1000" data-brand="Andrew">shoe1</div><br />
<div class="content" data-category="shirts" data-price="1200" data-brand="Sunbaby">shirt1</div><br />
<div class="content" data-category="shoes" data-price="2000" data-brand="Andrew">shoe2</div><br />
<div class="content" data-category="shoes" data-price="800" data-brand="Andrew">shoe3</div><br />
<div class="content" data-category="shirts" data-price="1300" data-brand="Sunbaby">shirt2</div><br />
<div class="content" data-category="shirts" data-price="800" data-brand="Sunbaby">shirt3</div><br />
<input type="checkbox" class="category" category="shoes" id="shoes">shoes
<input type="checkbox" class="category" category="shirts" id="shirts">shirts
<input type="radio" name="range" value="0-9000" checked>All
<input type="radio" name="range" value="0-999">0-1000
<input type="radio" name="range" value="1000-2000">1000-2000
Basically if you select a category from checkbox lets say shoes, then divs only with shoes should get displayed. Then if you filter the results with price, some starting and ending limit, it should show shoes category divs falling in that specific range, Not out of that range.
And in between if you select brand checkbox also.then it should match for all the three checkboxes that is from category and brand and price range
For example:- we selected shoes checkbox, it should show shoe divs; then if we select range as 1000-2000, then it should show shoe1 and shoe2 and not shoe3.
if u select shoe category and then if you select brand checkbox as well.it should filter out on both checkbox basis,and then it should look for price range and match the results,filter the divs.
Please help on this.
<script type="text/javascript">
$("input.category").prop("checked", true).change(function (e) {
$("input[name=range]:checked").trigger("change");
});
$("input.brand").prop("checked", true).change(function (e1) {
$("input[name=range]:checked").trigger("change");
});
$("input[name=range]").change(function (e) {
var toggle = this.checked;
var range = this.value.split('-');
var rangeFrom = parseInt(range[0]);
var rangeTo = parseInt(range[1]);
$(".content[data-price]").each(function(){
var $this = $(this);
var categoryActive = $("#" + $this.data("category")).prop("checked");
var brandActive = $("#" + $this.data("brand")).prop("checked");
var price = parseFloat($this.data('price'));
$this.toggle(price >= rangeFrom && price <= rangeTo && categoryActive);
$this.toggle(price >= rangeFrom && price <= rangeTo && $("#" + $this.data("brand")).prop("checked"));
});
});
</script>
i tried this script with my one buddy's help.
Thanks and Google if You can help on this
you can do something like this :
$("#shoes").click(function (e) {
$('.content[data-category=shoes]').toggle();
});
Solution
HTML
<form id="filter">
<div>
<input type="checkbox"
name="brand"
value="Andrew"
checked>Andrew
</input>
<input type="checkbox"
name="brand"
value="Sunbaby"
checked>Sunbaby
</input>
<input type="checkbox"
name="brand"
value="Nike"
checked>Nike
</input>
</div>
<div>
<input type="checkbox"
name="category"
value="shoes"
checked>Shoes
</input>
<input type="checkbox"
name="category"
value="shirts"
checked>
Shirts
</input>
</div>
<div>
<input type="radio"
name="price"
value="0-9000"
checked>All
</input>
<input type="radio"
name="price"
value="0-999">0-1000
</input>
<input type="radio"
name="price"
value="1000-2000">1000-2000
</input>
<div>
</form>
CSS
.hidden {display: none;}
JS/JQUERY
var filterContentForm = function(content, form){
var filter = function() {
var checkBoxGroups = {},
radioGroups = {};
var addRadioGroup = function(name){
radioGroups[name] = {
el: $('input[name='+name+']:checked')
};
var n = radioGroups[name];
n.el
.each(function(){
n.range = $(this).val().split('-');
n.from = Number(n.range[0]);
n.to = Number(n.range[1]);
});
};
$('#filter input[type=radio]')
.each(function(){
addRadioGroup($(this).attr('name'));
});
var addCheckBoxGroup = function(name){
checkBoxGroups[name] = {
el: $('input[name='+name+']:checked'),
ch: []
};
var n = checkBoxGroups[name];
n.el.each(function(){
n.ch.push($(this).val());
});
};
$('#filter input[type=checkbox]')
.each(function(){
addCheckBoxGroup($(this).attr('name'));
});
var contents = $(content), all = 0;
contents.removeClass('hidden')
.each(function(){
var $this = $(this),
price = $this.data('price');
for(var c in radioGroups){
var n = radioGroups[c],
d = Number($this.data(c));
if(d < n.from || d > n.to){
$this.addClass('hidden');
all++;
return;
}
}
var show = 0, i;
for(var c in checkBoxGroups){
var n = checkBoxGroups[c],
d = $this.data(c);
for(i = 0; i < n.ch.length; i++){
if(d === n.ch[i]) {
show++; break;
}
}
}
var l = Object.keys(checkBoxGroups).length;
if(show < l) {
$this.addClass('hidden');
all++;
}
});
if(all > contents.length - 1)
contents.removeClass('hidden');
};
$(form+' input').change(filter);
filter();
};
filterContentForm('.content', '#filter');