I'm struggling with this code, I've two js that dynamically change the price of a div with id=#prezzo.
My problem is that I have a basic price of 1000 and I want that price to be overridden when I click on one of the three buttons (and not be overridden when I click on checkboxes).
var basicPrice = 1000; // This is how we start
function getCheck() {
var currentPrice = basicPrice; // every time
currentPrice += parseFloat($(".event-hook-class.active").data("prezzo")) || 0, // add any "active" boxes
services = [],
total = 0;
console.log(currentPrice)
$("input[id^=service]").each(function() {
if (this.checked) {
total += +this.value;
services.push($("[for=" +this.id + "]").html()); // get the label text
}
});
$("#prezzo").text((currentPrice + total).toFixed(2) + "€");
$("#serv").html("services: " + services.join(", "));
}
$(document).ready(function() {
$("input[id^=service]").on("click", getCheck);
$(".event-hook-class").on("click",function(e) {
e.preventDefault();
$(".event-hook-class").removeClass("active");
$(this).addClass("active")
$("#prezzo").html($(this).data('prezzo') + ' €');
$("#mq").html($(this).data('mq'));
getCheck(); // will add this and the checkboxes
});
getCheck(); // initialise on page load
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="event-hook-class simple-text piano" id="C.1_1" data-prezzo="1080.56" data-mq="94">
C.1_1 <br> piano 1<br> prezzo 1080.56 €</button><br><button type="button" class="event-hook-class simple-text piano" id="D.1_1" data-prezzo="1084.72" data-mq="94">
D.1_1 <br> piano 1<br> prezzo 1084.72 €</button><br><button type="button" class="event-hook-class simple-text piano" id="C_2.1" data-prezzo="1109.68" data-mq="94">
C_2.1 <br> piano 2<br> prezzo 1109.68 €</button><br>
<form id="services" name="services-form" data-name="services Form">
<div class="checkbox-field w-checkbox"><input type="checkbox" value="22500" id="service_1" name="checkbox" data-name="Checkbox" class="checkbox 1 w-checkbox-input"><label for="service_1" class="simple-text white w-form-label">design pack</label> 22500 €</div>
<div class="checkbox-field ew w-checkbox"><input type="checkbox" value="2000 " id="service_2" name="checkbox-2" data-name="service_2" class="checkbox 2 w-checkbox-input"><label for="service_2" class="simple-text white w-form-label">security</label> 2000 €</div>
<div class="checkbox-field 2 w-checkbox"><input type="checkbox" value="5000" id="service_3" name="checkbox-2" data-name="service_3" class="checkbox 3 w-checkbox-input"><label for="service_3" class="simple-text white w-form-label">wellness pack</label> 5000 €</div>
<div class="checkbox-field 4 w-checkbox"><input type="checkbox" value="1000" id="service_4" name="checkbox-2" data-name="service_4" class="checkbox 4 w-checkbox-input"><label for="service_4" class="simple-text white w-form-label">box auto</label> 1000 €</div>
</form>
<div class="paragraph" id="prezzo">
1000 €</div>
<div id="display_services" class="simple-text maiusc prova">services:<br>design pack<br>dynamically adding the services...</div>
I'm new to js world, so I don't know how to do it:
Change current price variable to choose between active button price and basic price in getCheck function:
var basicPrice = 1000; // This is how we start
function getCheck() {
var currentPrice = parseFloat($(".event-hook-class.active").data("prezzo")) || basicPrice, // add any "active" boxes
services = [],
total = 0;
console.log(currentPrice);
$("input[id^=service]").each(function() {
if (this.checked) {
total += +this.value;
services.push($("[for=" +this.id + "]").html()); // get the label text
}
});
$("#prezzo").text((currentPrice + total).toFixed(2) + "€");
$("#serv").html("services: " + services.join(", "));
}
Related
I have a function that calculates sum of input values. In this form I have checkboxes and number type inputs. I'm able to make this function work with either only checkboxes or textboxes but not both at the same time. The two input types enter in conflict. It's probably very trivial but I can't seem to figure it out. Any help?
js
$(document).on("change", ".calculate", function () {
calculateTotal();
});
function calculateTotal() {
//input type number
var textboxsum = 0;
//input type checkbox
var addonsum = 0;
//iterate through each input
$(".calculate").each(function () {
//get input type
var type = this.getAttribute("data-type");
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === "room") {
//add amount $35 per room
var amount = parseFloat(this.value * 35);
} else if (type === "addon") {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat(this.value * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() roundoff to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
there are few issues in the code, and you can use parseInt instead of parseFloat
$('.calculate').change(function() {
let amount = 0;
$(".calculate").each(function() {
const type = this.getAttribute('data-type');
if (!isNaN(this.value) && this.value.length !== 0) {
if (type === 'room') {
//add amount $35 per room
amount = parseInt(this.value, 10) * 35;
} else if (type === 'addon' && this.checked) {
amount += parseInt(this.value, 10) * 10;
}
}
});
$(".total_amount").html(amount.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>
Total : <span class="total_amount">0</span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>
Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr>
Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
You have to declare var amount = 0; at top inside .each(). The reason you are getting NaN when type is not room then it will not execute code from if(type==='room') where you have declared amount and in end you have used textboxsum += parseFloat(amount);, so here amount will return undefined & textboxsum will become NaN.
Try it below.
$(document).on('change', '.calculate', function() {
calculateTotal();
});
function calculateTotal() {
//from input type number
var textboxsum = 0;
//from input type checkbox
var addonsum = 0;
//iterate through each textboxes and add the values
$(".calculate").each(function() {
//get input type
var type = this.getAttribute('data-type');
// declare amount variable here
var amount = 0; // <-- Change
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
if (type === 'room') {
//add amount $35 per room
// do not declare variable here. just use it
amount = parseFloat((this.value) * 35);
} else
if (type === 'addon') {
var input = document.getElementsByName("checkbox");
for (var i = 0; i < input.length; i++) {
if (this.checked) {
//10$ per addon
addonsum += parseFloat((this.value) * 10);
}
}
}
textboxsum += parseFloat(amount);
}
});
//addup the two totals
var totalAmount = textboxsum + addonsum;
//.toFixed() method will roundoff the final sum to 2 decimal
$(".total_amount").html(totalAmount.toFixed(2));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>book a vacation house</h3>
<hr>Total : <span class="total_amount"></span>
<hr>
<input type="number" data-type="room" class="calculate" min="0" placeholder="Number of Rooms">
<hr>Fireplace
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Pool
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Jacuzzi
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
<hr> Mini Bar
<input type="checkbox" name="checkbox" value="1" data-type="addon" class="calculate">
I am struggling with this thing for the last few days and trying to obtain specific div details. It was resolved actually and here is the working one - Obtain Related Div Text with jQuery. So if you have seen it, I was using individual buttons for each div section as follows:
<div class="divs">
<div class="heading">
<div class="h2Val"> //Trying to retrieve this value - The id
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
//Another one is this - CheckBox value
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
<div>
<input type="button" class="btn" value="Get Value" /> //This is the button that was assigned with every div
</div>
</div>
</div>
But now, I am trying to separate the buttons and used anchor tag that's out of the parent div class divs to retrieve those values . But the issue is, it doesn't get the id and values of individual divs. Here is the code snippet:
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $(this).closest('.heading')
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function(){
return this.value
}).get();
console.clear()
console.log('ID: ' + id +' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divs">
<div class="heading">
<div class="h2Val">
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">
2
</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
So I tweaked a bit with the following but it retrieves all the selected div values at a time rather than individual:
$(".button").click(function() { //This doesn't get the id and value of heading div
var $container = $('.divs').children().closest('.heading')
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function(){
return this.value
}).get();
console.clear()
console.log('ID: ' + id +' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
});
});
Any better way or solution to resolve it?
Update 1: Expected output - When checked on first option and clicked Next, it should show result as follows:
ID: 1 has 1 checked
Values: London
Then when second question comes and the same should happen:
ID: 2 has 1 checked
Values: Charles Babbage
You can get length of .divs and then declare some variable which will have value 0 .So, whenever next button is clicked you can check if the variable value if less then the length of .divs and depending on this either increment value by 1 or start counter again from 0.
Demo Code :
$(document).ready(function() {
divs = $(".divs").children();
divs.each(function(e) {
if (e != 0)
$(this).hide();
});
var index = 0,
divs = $(".divs").children();
$("#next").click(function() {
index = (index + 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
$("#prev").click(function() {
index = (index - 1) % divs.length;
divs.eq(index).show().siblings().hide();
})
//declare
var indexes = 0;
$(".button").click(function() {
//get div length
var lengths = divs.length;
//pass indexes value to get required div
var $container = $('.divs').children().eq(indexes);
var id = $container.find(".h2Val").text().trim();
var $checked = $container.find('.cbCheck:checked');
var values = $checked.map(function() {
return this.value
}).get();
console.clear()
console.log('ID: ' + id + ' has ' + $checked.length + ' checked');
console.log('Values: ', values.join())
//checking if indexes value is less then length of div
if (indexes < (lengths-1)) {
//increment
indexes++;
} else {
//start from 0
indexes = 0;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="divs" datas="abc">
<div class="heading">
<div class="h2Val">
1
</div>
<div>What's the capital of England?</div>
<div class="heading2">
<div>
<input type="checkbox" id="val1" class="cbCheck" name="val1" value="London" />London</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val2" class="cbCheck" name="val2" value="New York" />New York</div>
</div>
</div>
<div class="heading">
<div class="h2Val">
2
</div>
<div>Who invented computer?</div>
<div class="heading2">
<div><input type="checkbox" id="val3" class="cbCheck" name="val3" value="Thomas Edison" />Thomas Edison</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val4" class="cbCheck" name="val4" value="Charles Babbage" />Charles Babbage</div>
</div>
<div class="heading2">
<div><input type="checkbox" id="val5" class="cbCheck" name="val5" value="Sir Isaac Newton" />Sir Isaac Newton</div>
</div>
</div>
</div>
<a class="button" id="prev">Previous</a>
<a class="button" id="next">Next</a>
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 have a form with 5 questions and 3 different answers for each question.
e.g.
q1. whats is your favorite color?
radio button-1. value blue
radio button-2. value red
radio button-3. value grey
most of these questions have the same value (blue, red, grey), which is what I want, however, I'm trying to add all the values together at the end of the form so I can determine if the person filling out the form equals one of the values (blue, red, or grey).
I'm building this form with angularjs and this is what i have so far.
<label>Q1. what is your favorite color?</label>
<div class="form-group">
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="blue">
blue
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="red">
red
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData.color" value="grey">
grey
</label>
</div>
this bit of code only works if I have the values already entered into the variable
$scope.formData = { };
$scope.formData = [];
$scope.formData.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < $scope.formData.length; i++) {
if ($scope.formData[i] != current) {
if (cnt > 0) {
console.log(current + ' shows ' + cnt + ' times');
}
current = $scope.formData[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
console.log(current + ' shows ' + cnt + ' times');
}
Here is an example solution plunker. Would it work?
controller
$scope.questions = [
'Q1. what is your favorite color?',
'Q2. what color is your car?',
'Q3. what color best represents you?'
];
$scope.formData = [];
$scope.stats = function() {
$scope.results = {};
for (var i = 0; i < $scope.formData.length; i++) {
var color = $scope.formData[i];
if(color) {
if ($scope.results.hasOwnProperty(color)) {
$scope.results[color]++;
} else {
$scope.results[color] = 1;
}
}
}
};
template
<div class="form-group" ng-repeat="q in questions">
<label>{{q}}</label>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="blue">blue
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="red">red
</label>
</div>
<div class="radio">
<label>
<input type="radio" ng-model="formData[$index]" value="grey">grey
</label>
</div>
</div>
<button ng-click="stats()">show results</button>
<ul>
<li ng-repeat="(c, n) in results"> {{c}} shows {{n}} times</li>
</ul>
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.