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

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>

Related

JavaScript Total Price List Not Displaying

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

how to validate my input type radio in my Multistep form? When I click Next Then its forworded to next step

I am using the multistep form and I want to prevent input radio in step form if the radio is not selected then not forward another step. My input type of text is validated.
allNextBtn.click(function(e) {
e.preventDefault();
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]')
.parent()
.next()
.children("a"),
**curInputs = curStep.find(
"input[type='text'],input[type='url'],input[type='email'],input[type='phone'],input[type='date']"
),**
isValid = true;
$(".form-group").removeClass("alert alert-danger");
$(".msg_error").html("");
for (var i = 0; i < curInputs.length; i++) {
if (!curInputs[i].validity.valid) {
isValid = false;
$(curInputs[i])
.closest(".form-group")
.addClass(" alert alert-danger");
$(".msg_error").html("All fields are mandatory.");
}
//console.log(!curInputs[i].validity.valid);
}
<input type="radio" name="customer_budget" value="$0 - $15,000">
<input type="radio" name="customer_budget" value="$15,001 - $30,000">
<input type="radio" name="customer_budget" value="$30,001 - $50000">
<input type="radio" name="customer_budget" value="$50,001 - Above">
function getSelectedRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
}
function result() {
var score = 0;
score += parseInt(getSelectedRadioValue("q1")) || 0;
score += parseInt(getSelectedRadioValue("q2")) || 0;
score += parseInt(getSelectedRadioValue("q3")) || 0;
score += parseInt(getSelectedRadioValue("q4")) || 0;
document.getElementById('result').innerHTML = ("You selected " + score);
document.getElementById("questions").style.display = 'none';
document.getElementById('result').style.display = 'block';
}
window.onload = function() {
check.onclick = result;
}
<body>
<div class="topnav">
</div><br><br>
<div class="center123">
<br>
<div id="questions" class="divhide">
<div class="divh2">
<b>1) What is the square root of 64?</b>
<div class="answers"><br>
<label class="radiobox">
<input class="radio" type="radio" value="9000" name="q1">9000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="60000" name="q2">60000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="8000" name="q3">8000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="12000" name="q4">12000
</label>
<br><br><br>
</div>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />
<input class="button" type="button" id="check" value="SUBMITT">
<font align="center" size="10" color="black">
</div>
<p id="result" style="display:none;">Result</p>
</font><br>
Next Step
</body>
Try this

Change the background of the radio button depending by the answer

I'm creating a mini quiz, if the answer is correct the background will be green, if is wrong will be red
here is the code of HTML
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="forma">
<div class="pyetja"><h3>1. The flag if Italy which color has..</h3>
<div class="formafoto"><div class="foto"></div><div class="pergjigjet"><div class="pergjigje">
<div class="pergjigjemajtas">
white and blue
</div>
<div class="pergjigjedjathtas" id="0">
<label><input type="radio" value="1" name="0" unchecked="">right</label>
<label><input type="radio" value="0" name="0" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigje">
<div class="pergjigjemajtas">
white and red
</div>
<div class="pergjigjedjathtas" id="1">
<label><input type="radio" value="1" name="1" unchecked="">right</label>
<label><input type="radio" value="0" name="1" unchecked="">wrong</label>
</div>
</div>
<div class="pergjigjeno">
<div class="pergjigjemajtas">
white red and green
</div>
<div class="pergjigjedjathtas" id="2">
<label><input type="radio" value="1" name="2" unchecked="">right</label>
<label><input type="radio" value="0" name="2" unchecked="">wrong</label>
</div>
</div></div></div></div>
<div class="question">
<input id="buton" type="button" value="Finish!" onClick="getScore(this.form); getResult(this.form);">
<p> <strong class="bgclr">Result = </strong><strong><input class="bgclr1" type="text" size="2" name="percentage" disabled></strong><br><br>
<div id="rezultati"></div>
</div>
</form>
</body>
</html>
and javascript
// Insert number of questions
var numQues = 3;
// Insert number of choices in each question
var numChoi = 2;
// Insert number of questions displayed in answer area
var answers = new Array(2);
// Insert answers to questions
answers[0] = 1;
answers[1] = 1;
answers[2] = 1;
// Do not change anything below here ...
function getScore(form) {
var score = 0;
var currElt;
var currSelection;
for (i=0; i<numQues; i++) {
currElt = i*numChoi;
for (j=0; j<numChoi; j++) {
currSelection = form.elements[currElt + j];
if (currSelection.checked) {
if (currSelection.value == answers[i]) {
score++;
}
}
}
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
if(score > 3) {
document.getElementById("rezultati").innerHTML = "Congratulation!";
} else {
document.getElementById("rezultati").innerHTML = "Try again!";
}
form.percentage.value = score;
form.solutions.value = correctAnswers;
}
// End -->
</script>
I get always red background and if the answer is correct, maybe document.getElementByName("0").value is not getting a number to make true the condition
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
document.getElementById("0").style.backgroundColor="#00FF00";
} else {
document.getElementById("0").style.backgroundColor="#e83f3f";
}
var radio1 = document.getElementByName("0").value;
if (answers[0] == radio1) {
Probably your error is in this line of code, the id="0" is a div and you are trying to get the value of it, this might result into undefined and the value answer[0] is 1, thus 1 is not equal to radio1, thus it is always getting into the else block.

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

Hide and show product list on basis of multiple categories in javascript

<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');

Categories

Resources