How to compute a total using Javascript - javascript

I'm working on a restaurant menu and with this I've create burgers, fries, and drinks as check boxes. when you click on burgers or fries or drinks options appear for you to choose from like a burger with cheese or a burger plain or with bacon or with both is available. Also with fries you can choose small medium or large and drinks have soda or bottled water. My question was how to compute the total of said items
Burgers
Regular (4.19)
w/ Cheese (4.79)
w/ Bacon (4.79)
w/ Bacon and Cheese (5.39)
Fries
Small (2.39)
Medium (3.09)
Large (4.99)
Drinks
Soda (1.69)
Bottled Water (1.49)
and with the advice I received I created this with the desire result I was seeking.
<!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" value="4.19" /><label
for="radBurgerRegular">Regular (4.19)</label><br />
<input type="radio" name="radBurgers" id="radBurgerCheese" value="4.79" /><label
for="radBurgerCheese">w/ Cheese (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBacon" value="4.79" /><label
for="radBurgerBacon">w/ Bacon (4.79)</label><br />
<input type="radio" name="radBurgers" id="radBurgerBaconCheese" value="5.39" /><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" value="2.39" /><label
for="radFriesSmall">Small (2.39)</label><br />
<input type="radio" name="radFries" id="radFriesMedium" value="3.09" /><label
for="radFriesMedium">Medium (3.09)</label><br />
<input type="radio" name="radFries" id="radFriesLarge" value="4.99" /><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" value="1.69" /><label
for="radDrinkSoda">Soda (1.69)</label><br />
<input type="radio" name="radDrinks" id="radDrinkWater" value="1.49" /><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="week11.css">
<script src="week11.js"></script>
</body>
</html>
Javascript:
var total = parseFloat(document.getElementById('txtTotal').value);
function ToggleBurgers() {
var chkBurgers = document.getElementById('chkBurgers');
var burgers = document.getElementById('divBurgers');
if (chkBurgers.checked) {
burgers.style.visibility = 'visible';
} else {
burgers.style.visibility = 'hidden';
}
}
function ToggleFries() {
var chkFries = document.getElementById('chkFries');
var fries = document.getElementById('divFries');
if (chkFries.checked) {
fries.style.visibility = 'visible';
} else {
fries.style.visibility = 'hidden';
}
}
function ToggleDrinks() {
var chkDrinks = document.getElementById('chkDrinks');
var drinks = document.getElementById('divDrinks');
if (chkDrinks.checked) {
drinks.style.visibility = 'visible';
} else {
drinks.style.visibility = 'hidden';
}
}
function ComputeTotal() {
var total = 0;
if(document.getElementById('chkBurgers').checked){
if(document.getElementById('radBurgerRegular').checked){
total += 4.19;
}
if(document.getElementById('radBurgerCheese').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBacon').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBaconCheese').checked){
total += 5.39;
}
}
if(document.getElementById('chkFries').checked){
if(document.getElementById('radFriesSmall').checked){
total += 2.39;
}
if(document.getElementById('radFriesMedium').checked){
total += 3.09;
}
if(document.getElementById('radFriesLarge').checked){
total += 4.99;
}
}
if(document.getElementById('chkDrinks').checked){
if(document.getElementById('radDrinkSoda').checked){
total += 1.69;
}
if(document.getElementById('radDrinkWater').checked){
total += 1.49;
}
}
document.getElementById('txtTotal').value = total;
}
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;
}
window.onload = init;

I think this question is OK for Stack. It's a bit tutorialy, but at least code has been provided, etc...
Anyway, on with the code:
function ComputeTotal() {
var total = 0;
if(document.getElementById('chkBurgers').checked){
if(document.getElementById('radBurgerRegular').checked){
total += 4.19;
}
if(document.getElementById('radBurgerCheese').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBacon').checked){
total += 4.79;
}
if(document.getElementById('radBurgerBaconCheese').checked){
total += 5.39;
}
}
if(document.getElementById('chkFries').checked){
// -- etc. etc.
}
// -- etc. etc.
document.getElementById('txtTotal').value = total;
}
You could improve the code by setting the "value" of the radio button to be the price. e.g.
<input type="radio" name="radBurgers" id="radBurgerRegular" value="4.19" /><label for="radBurgerRegular">Regular (4.19)</label>
You could then just do something like:
total += document.getElementById('radBurgerRegular').checked ? parseFloat(document.getElementById('radBurgerRegular').value) : 0;
for each radio button.
You could even wrap that up in a function, something like:
total += addValueOf('radBurgerRegular'); // -- for each line
and set the function to be:
function addValueOf(elementId){
return document.getElementById(elementId).checked ? parseFloat(document.getElementById(elementId).value : 0;
}
You could definitely write it quicker, neater, better and prettier with jQuery, but it's good to learn the building blocks first -- keep it up!

Related

create dropdown with multiple selection in JS

I want to implement a dropdown similar to the one on Booking.com in terms of functionality (I attach a screenshot), but I am encountering some issues and I can't figure out where I'm going wrong. Do you have any suggestions?
HTML
<div class="dropdown">
<input type="text" id="droptxt" class="list" readonly placeholder="Number of guests">
<div id="content" class="content">
<div class="list">
<input type="checkbox" id="rooms" class="list" value="Choose how many rooms" />
<label for="Choose how many rooms" class="list">Choose how many rooms </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="adults" class="list" value="Choose the number of adults" />
<label for="Choose the number of adults" class="list">Choose the number of adults </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
<div class="list">
<input type="checkbox" id="children" class="list" value="Choose the number of children" />
<label for="Choose the number of children" class="list">Choose the number of children </label>
<input type="hidden" class="list quantity" min="1" value="1" />
</div>
</div>
</div>
JavaScript
const txt = document.getElementById('droptxt');
console.log(txt);
const content = document.getElementById('content');
console.log(content);
const checkboxes = document.querySelectorAll('.list input[type="checkbox"]');
const quantity = document.querySelectorAll('.list input[type="number"]');
txt.addEventListener('click', function() {
content.classList.toggle('show');
});
// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
if (!e.target.matches('.list')) {
if (content.classList.contains('show')) content.classList.remove('show');
}
};
checkboxes.forEach(function(checkbox, index) {
checkbox.addEventListener('click', function() {
quantity[index].type = (checkbox.checked) ? 'number' : 'hidden';
calc();
});
});
quantity.forEach(function(input) {
input.addEventListener('input', calc);
});
function calc() {
let arr = [];
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
arr.push(quantity[i].value + ' x ' + checkboxes[i].value);
}
}
txt.value = arr.join(', ');
}
const quantity = document.querySelectorAll('.list input[type="number"]');
in this line you are selecting input[type="number"] but in your html there is no input which type is number. use this
const quantity = document.querySelectorAll('.list input[type="hidden"]');
it will solve your problem

One submit button works on my form the other one refreshes the website while updating the url

Im trying to make a quiz using forms and the top submit button works perfectly while the bottom button does not work it ends up refreshing the page and it says the field selected in the address bar this is for a project for college and im a beginner to JavaScript if someone could help me out and explain how it works that would be great I understand how the script works with one from and one button and what the code does but im confused when it comes to 2 forms
var form = document.querySelector("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
form.addEventListener("submit", function(event) {
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText = output;
event.preventDefault();
pointsAdd();
}, false);
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<header>
<ul class="navbar">
<li>Home</li>
<li>Poland</li>
<li>Russia</li>
<li>Uzbekistan</li>
</ul>
</header>
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log">
</pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>
You have TWO forms. so you need an event handler for each
You have ONE log element so I suggest you might want to append the result
Move the preventDefault to the top of the handler to not have a later error submit the form
NOTE: Header ALSO goes in the body (but is irrelevant to your question).
var forms = document.querySelectorAll("form");
var log = document.querySelector("#log");
var points = 0;
var q1QuizAns = 0;
var q2QuizAns = 0;
forms.forEach(form => form.addEventListener("submit", function(event) {
event.preventDefault();
var data = new FormData(form);
var output = "";
for (const entry of data) {
output = output + entry[0] + "=" + entry[1] + "\r";
q1QuizAns = entry[1];
q2QuzAns = entry[1];
};
log.innerText += output;
pointsAdd();
}))
function pointsAdd() {
if (q1QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
} else if (q2QuizAns == 1) {
points = points + 1;
logPoints.innerText = points;
}
}
<div class="testBody">
<div class="bodyText">
<h1>Poland Test</h1>
<form>
<p>Please select your preferred contact method:</p>
<div>
<input type="radio" id="contactChoice1" name="question1" value="1">
<label for="contactChoice1">Warsaw</label>
<input type="radio" id="contactChoice2" name="question1" value="2">
<label for="contactChoice2">Krakow</label>
<input type="radio" id="contactChoice3" name="question1" value="3">
<label for="contactChoice3">Straszyn</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<form>
<p>What is the national animal of Poland</p>
<div>
<input type="radio" id="Question2Choice1" name="question2" value="1">
<label for="Question2Choice1">White-Tailed Eagle</label>
<input type="radio" id="Question2Choice2" name="question2" value="2">
<label for="Question2Choice1">Black-Tailed Eagle</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
<!-------------------------------------------------------------------------->
<pre id="log"></pre>
<pre id="logPoints"></pre>
<!-------------------------------------------------------------------------->
</div>
</div>

How do I reset the numbers after calculating the Total

How will I clear the total after the first calculation?
I want it to reset if I add a new item after the first calculation. Right now it's adding it to the previous one.
For example, for the first calculation (item1 + item2) = total
if I add another item, it becomes (item1 + item 2) + (item1 + item2 + item3) = total
What I want is for it to reset and calculate the new total with the new item added.
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate()
{
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.textContent += count;
taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
Total.textContent += ((tax*count) + count).toFixed(2);
}
btn.addEventListener('click',Calculate);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column" >
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</div>
<script src="java.js"></script>
</body>
</html>
You should:
Declare the count variable inside the Calculate function, so that it starts from 0 every time the button is clicked
Instead of +=ing to the ItemTotal, TotalWithTax, etc fields, create an inner element that you assign to the text to instead. So, for example, instead of
<p id="ItemTotal"> Item Total: </p>
use:
<p> Item Total: <span id="ItemTotal"></span></p>
This way, whenever the button is clicked, you can simply assign to the ItemTotal, overwriting whatever was there previously.
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks = document.querySelectorAll('.items');
var ItemTotal = document.getElementById('ItemTotal');
var Total = document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
function Calculate() {
let count = 0;
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
count += parseFloat(checks[i].value);
}
}
ItemTotal.textContent = count;
taxFeild.textContent = (parseFloat(tax * count).toFixed(2));
Total.textContent = ((tax * count) + count).toFixed(2);
}
btn.addEventListener('click', Calculate);
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column">
<div id="Sums">
<p> Item Total: <span id="ItemTotal"></span></p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
</div>
</div>
</div>
You might also consider surrounding the inputs with <label>s, to make them more clickable:
var taxRate = 0.05;
var checks = document.querySelectorAll('.items');
var subtotalSpan = document.getElementById('ItemTotal');
var taxSpan = document.getElementById("Tax");
var totalSpan = document.getElementById('TotalWithTax');
function Calculate() {
let subtotal = 0;
for (var i = 0; i < checks.length; i++) {
if (checks[i].checked) {
subtotal += parseFloat(checks[i].value);
}
}
const tax = taxRate * subtotal;
const total = tax + subtotal;
subtotalSpan.textContent = subtotal;
taxSpan.textContent = tax.toFixed(2);
totalSpan.textContent = total.toFixed(2);
}
var btn = document.getElementById("btn");
btn.addEventListener('click', Calculate);
#checkBoxes > label {
cursor: pointer;
}
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<label><input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)</label><br>
<label><input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)</label><br>
<label><input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)</label><br>
<label><input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)</label><br>
<label><input type="checkbox" class="items" value='5.99'> Side salad ($5.99)</label><br>
<button id="btn">Calculate</button>
</div>
</div>
<div class="column">
<div id="Sums">
<p> Item Total: <span id="ItemTotal"></span></p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
</div>
</div>
</div>
You can use the onblur event on your calculator button. The onblur event occurs when you click off of an object. After a user clicks the "calculate" button, when they click anywhere else, the onblur function will call.
You can find out more about the onblur event at: https://www.w3schools.com/jsref/event_onblur.asp
W3Schools has a lot of easy to learn information. Here are other events which may prove to be useful in the future (or for expanding this project): https://www.w3schools.com/jsref/dom_obj_event.asp
A simple reset function can reset your counter and your paragraph tags.
var count = 0;
var tax = 0.05;
var taxFeild = document.getElementById("Tax");
var checkBoxes = document.getElementById("checkBoxes");
var checks=document.querySelectorAll('.items');
var ItemTotal=document.getElementById('ItemTotal');
var Total=document.getElementById('TotalWithTax');
var btn = document.getElementById("btn");
// RESET YOUR CALCULATOR FIELDS & COUNT
function resetCalc(){
count = 0;
ItemTotal.textContent = "Item Total: ";
taxFeild.textContent = "Tax: ";
Total.textContent = "Total with Tax: ";
}
function Calculate()
{
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.textContent += count;
taxFeild.textContent += (parseFloat(tax*count).toFixed(2));
Total.textContent += ((tax*count) + count).toFixed(2);
}
btn.addEventListener('click',Calculate);
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2 class="first-heading">Assignment 1</h2>
<div class="row">
<div class="column">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99'>Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99'> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='7.99'> Hamburger ($7.99)<br>
<input type="checkbox" class="items" value='12.99'> Grilled salmon($12.99)<br>
<input type="checkbox" class="items" value='5.99'> Side salad ($5.99)<br>
<!-- NOTICE THE ONBLUR -->
<button id="btn" onblur="resetCalc();">Calculate</button>
</div>
</div>
<div class="column" >
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</div>
<script src="java.js"></script>
</body>
</html>
Problem seems to be plus sign when asigning content. Just replace += with = and it should work
ItemTotal.textContent = count;
taxFeild.textContent = (parseFloat(tax*count).toFixed(2));
Total.textContent = ((tax*count) + count).toFixed(2);
And place captions in span like this:
<p> Item Total:<span id="ItemTotal"></span> </p>
<p> Tax: <span id="Tax"></span></p>
<p>Total with Tax: <span id="TotalWithTax"></span></p>
You can add count = 0; on the first line of function Calculate() { .... } so it will gives you a new total every time your list changes.
To update the field and keep the content intact.
const taxValue = tax * count;
total = taxValue + count;
ItemTotal.innerText = "Item Total:" + count;
taxFeild.innerText = "Tax:" + (parseFloat(taxValue).toFixed(2));
Total.innerText = "Total with Tax:" + (parseFloat(total).toFixed(2));

Grading a test - Loop checking radio input values (JS)

I am working on an online test where you get your output directly. I get stuck at checking the values of the radio input with a loop. Why gives the checkFields function output undefined?
Javascript Code:
<script type="text/javascript">
$(document).ready(function(){
//click button
$("#submitTest").click(function(){
//check if all answers are given
for (i = 1; i <= 10; i++) {
if (checkFields([i].toString())) {
//calculate total score
if ($("input[name=[i]]").val() == aq[i]) {score = score + 1};
}
else{alert("Please answer all questions");
break}};
console.log(score);
//return level of English
}
)
//setFunction
function checkFields(Q){
console.log(
$("[name='[Q]']:checked").val())
}
//Set score 0
var score = 0;
//Answers
var aq1 = "a1";
var aq2 = "a1";
var aq3 = "a3";
var aq4 = "a2";
var aq5 = "a1";
var aq6 = "a2";
var aq7 = "a3";
var aq8 = "a3";
var aq9 = "a1";
var aq10 = "a1";
}
)
</script>
HTML code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- liberaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<!-- Q1 -->
<p class="question">1. Can I park here?</p>
<input type="radio" id="1" name="1" value="a1">a1<br>
<input type="radio" id="1" name="1" value="a2">a2<br>
<input type="radio" id="1" name="1" value="a3">a3
<!-- Q2 -->
<p class="question">2. Can I park here?</p>
<input type="radio" name="2" value="a1">a1<br>
<input type="radio" name="2" value="a2">a2<br>
<input type="radio" name="2" value="a3">a3
<!-- Q3 -->
<p class="question">3. Can I park here?</p>
<input type="radio" name="3" value="a1">a1<br>
<input type="radio" name="3" value="a2">a2<br>
<input type="radio" name="3" value="a3">a3
<!-- Q4 -->
<p class="question">4. Can I park here?</p>
<input type="radio" name="4" value="a1">a1<br>
<input type="radio" name="4" value="a2">a2<br>
<input type="radio" name="4" value="a3">a3
<!-- Q5 -->
<p class="question">5. Can I park here?</p>
<input type="radio" name="5" value="a1">a1<br>
<input type="radio" name="5" value="a2">a2<br>
<input type="radio" name="5" value="a3">a3
<!-- Q6 -->
<p class="question">6. Can I park here?</p>
<input type="radio" name="6" value="a1">a1<br>
<input type="radio" name="6" value="a2">a2<br>
<input type="radio" name="6" value="a3">a3
<!-- Q7 -->
<p class="question">7. Can I park here?</p>
<input type="radio" name="7" value="a1">a1<br>
<input type="radio" name="7" value="a2">a2<br>
<input type="radio" name="7" value="a3">a3
<!-- Q8 -->
<p class="question">8. Can I park here?</p>
<input type="radio" name="8" value="a1">a1<br>
<input type="radio" name="8" value="a2">a2<br>
<input type="radio" name="8" value="a3">a3
<!-- Q9 -->
<p class="question">9. Can I park here?</p>
<input type="radio" name="9" value="a1">a1<br>
<input type="radio" name="9" value="a2">a2<br>
<input type="radio" name="9" value="a3">a3
<!-- Q10 -->
<p class="question">10. Can I park here?</p>
<input type="radio" name="10" value="a1">a1<br>
<input type="radio" name="10" value="a2">a2<br>
<input type="radio" name="10" value="a3">a3
</form>
<!-- Submit -->
<button id="submitTest">Submit Test!</button>
</body>
</html>
This code might not be the way to do it. I tried various ways but did not manage.
edited below
New code
https://jsfiddle.net/5fnugrts/#&togetherjs=AOK0k8r4i2
HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Libaries -->
<script src="jquery-3.1.1.js"></script>
</head>
<body>
<!-- Form -->
<form id="testEnglish">
<div id="myForm"></div>
</form>
<!-- Submit button -->
<button id="submitTest">Submit Test!</button>
Javascript Code
<!-- JS -->
<script type="text/javascript">
$(document).ready(function() {
//Answers and Questions constructor ("question","answer1","answer2","answer3","a"+number of correct answer)
function Question(question, answer1, answer2, answer3, correctAnswer) {
this.q = question;
this.a1 = answer1;
this.a2 = answer2;
this.a3 = answer3;
this.ca = correctAnswer;
};
//Answers and Questions ("question","answer1","answer2","answer3","a"+number of correct answer)
var aQ = {
Q1: new Question("What is the correct answer 1?", "Cheese", "Ham", "Turkey", "a1"),
Q2: new Question("What is the correct answer 2?", "Cheese", "Ham", "Turkey", "a1"),
Q3: new Question("What is the correct answer 3?", "Cheese", "Ham", "Turkey", "a2"),
Q4: new Question("What is the correct answer 4?", "Cheese", "Ham", "Turkey", "a2"),
Q5: new Question("What is the correct answer 5?", "Cheese", "Ham", "Turkey", "a3"),
};
//Set Setinhtml function ("name of radio group" "question","answer1","answer2","answer3","a"+number of correct answer)
function appendQuestion(groupName, question, answer1, answer2, answer3) {
$("div#myForm").append("<p class=\"question\">" + question + "</p>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a1\">" + answer1 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a2\">" + answer2 + "<br>")
$("div#myForm").append("<input type=\"radio\" name=\"" + groupName + "\" value=\"a3\">" + answer3 + "<br>")
};
//Set in HTML loop
for (i = 1; i <= Object.keys(aQ).length; i++) {
appendQuestion([i],
eval("aQ.Q" + [i] + ".q"),
eval("aQ.Q" + [i] + ".a1"),
eval("aQ.Q" + [i] + ".a2"),
eval("aQ.Q" + [i] + ".a3"),
eval("aQ.Q" + [i] + ".ca"))
};
//Sumbit answers
$("#submitTest").click(function() {
score = 0
//Loop and give values
for (i = 1; i <= Object.keys(aQ).length; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = eval("aQ.Q" + i + ".ca")
//Check if answers are filled in
if (!tAnswer) {
alert("Please answer all questions");
return;
}
//Check correct answers
else if (tAnswer == cAnswer) {
score++
}
}
//Report score
alert("Your score is " + score + "/" + Object.keys(aQ).length);
});
});
</script>
I tweaked your code to make it more compact and effecient
Here's a codepen
$(document).ready(function() {
//Set score 0
var score = 0;
//Answers
aq1 = "a1";
aq2 = "a1";
aq3 = "a3";
aq4 = "a2";
aq5 = "a1";
aq6 = "a2";
aq7 = "a3";
aq8 = "a3";
aq9 = "a1";
aq10 = "a1";
$("#submitTest").click(function() {
score = 0
for (i = 1; i <= 10; i++) {
tAnswer = $("input:radio[name ='" + i + "']:checked").val()
cAnswer = window["aq"+i]
if (!tAnswer) {
alert("Please answer all questions");
return;
} else if (tAnswer == cAnswer) {
console.log("#"+i+": correct")
score++
} else if (tAnswer != cAnswer) {
console.log("#"+i+" incorrect")
}
}
alert("Your score is "+ score +"/10");
});
});
tAnswer is the answer and cAnswer is the correct answer, you can also check if(!cAnswer) then you didn't define the correct answer.

calculate value of Checked boxes using JS

I have the following html code:
I want to calculate the price associated with each checked box and display it in a text area after i click order (button). Pls help!
<div>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="submit" id = "submit_btn" onclick = "calculate()">
</fieldset>
</form>
</div>
This is usually not how it works on StackOverflow, you have to try fixing it yourself. However, I'm bored so here is a solution with HTML + Javascript.
It is bad practice to declare multiple ids with the same name, use classes instead. I changed your code a little bit. You said you want to display the code in another field, so using a form for this is not necessary.
var menuItems = document.getElementsByClassName('menuItem');
var orderButton = document.getElementById('order_btn');
var totalArea = document.getElementById('total');
var afn = 0;
orderButton.addEventListener('click', function(e) {
e.preventDefault();
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].checked) {
afn += +menuItems[i].value;
}
}
totalArea.innerHTML = "Total: " + afn + " AFN";
afn = 0;
});
<div>
<fieldset>
<legend>Resturant Menu:</legend>
<input type="checkbox" class="menuItem" value="300">
<label>Chicken-------------------------- 300 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="200">
<label>Chicken Baryani --------------- 200 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="250">
<label>Chicken Kabab ----------------- 250 AFN</label>
<br>
<input type="checkbox" class="menuItem" value="100">
<label>Juice ----------------------------- 100 AFN</label>
<br>
<button id="order_btn">Order</button>
</fieldset>
<p id="total">Total: 0 AFN</p>
</div>
function calculate(){
var allMenuItem = $('#menuItem input[type=checkbox]');
var totalPrice = 0;
$.each(allMenuItem, function(key, element){
if($(this).is(":checked")){
totalPrice += parseFloat($(this).val());
}
});
alert("You order price is: "+ totalPrice + " Rs");
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form>
<fieldset > <legend>Resturant Menu:</legend>
<div id="menuItem">
<input type="checkbox" id = "menu" value="300">
<label> Chicken-------------------------- 300 AFN</label> <br>
<input type="checkbox" id = "menu" value="200">
<label> Chicken Baryani --------------- 200 AFN</label> <br>
<input type="checkbox" id = "menu" value="250">
<label> Chicken Kabab ----------------- 250 AFN</label> <br>
<input type="checkbox" id = "menu" value="100">
<label> Juice ----------------------------- 100 AFN</label> <br>
<input type="button" value="Order" id = "submit_btn" onclick = "calculate()">
</div>
</fieldset>
</form>

Categories