How do I reset the numbers after calculating the Total - javascript

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

Related

Make multiple additions with multiple input value Javascript

I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.

how to replace name with an ID in javascript

I'm working on small programme and trying to make something that user can choose an item from the list "its like a resturant menu where the user choose their foods and it shows the prices and the tax", I used name="items[]" to get the values i was wondering if there is a way to use ID or Class instead of the name.Any help would be appreciated in advance .
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()
{
initVariable();
for(var i =0 ;i< checks.length;i++)
{
if(checks[i].checked)
{
count+=parseFloat(checks[i].value);
}
}
ItemTotal.innerHTML +=count;
taxFeild.innerHTML+=(parseFloat(tax*count));
Total.innerHTML+= (tax*count) + count;
}
btn.addEventListener('click',Calculate);
function initVariable()
{
count =0;
ItemTotal.innerHTML="Item Total: ";
taxFeild.innerHTML =" Tax: ";
Total.innerHTML ="Total with Tax: ";
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/>
<head>
<title>Test</title>
</head>
<body>
<div class = "container">
<div id="checkBoxes">
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)<br>
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)<br>
<input type="checkbox" class="items" value='12.99' id="item1"> Hamburger ($12.99)<br><br>
</div>
<button id="btn">Calculate</button>
<div id="Sums">
<p id="ItemTotal"> Item Total: </p>
<p id="Tax"> Tax: </p>
<p id="TotalWithTax">Total with Tax: </p>
</div>
</div>
</body>
</html>
If you have more than one its not correct to use same ID.
you can use de class and select it with document.querySelectorAll('.items')
The possible variants could be to use querySelectorAll or getElementsByClassName:
<input type="checkbox" class="items" value='7.99' id="item1">Fried Chicken ($7.99)
<input type="checkbox" class="items" value='9.99' id="item1"> Fried Halibut ($9.99)
<input type="checkbox" class="items" value='7.99' id="item1"> Hamburger ($7.99)
const checkboxes = document.getElementsByClassName('items');
// OR
const checkboxes = document.querySelectorAll('.items');
Or you still could use name attribute on input (instead of class):
const checkboxes = document.querySelectorAll('input[name="items[]"]');
You can select elements by their class. I would recommend using jQuery for this, but it can also be done in pure JavaScript. Let's assuming that we have three basic checkboxes (this is pseudo code):
<input type="checkbox" class="form-control" value="7.99">
<input type="checkbox" class="form-control" value="9.99">
<input type="checkbox" class="form-control" value="8.99">
<button class="btn btn-primary" type="button">
Calculate
</button>
We could use jQuery to iterate over each element with the class name ".form-control" in this scenario:
$(document).ready(function() {
const tax = 0.05;
$('.btn').on('click', function() {
let total = 0;
$('.form-control').each(function() {
if($(this).is(':checked')) {
let val = parseFloat($(this).val());
total += val;
}
});
if(total > 0) {
total += tax;
alert('Your total is $' + total);
}
});
});
Without jQuery you would do something such as:
const checks = document.getElementByClassName('form-control');
and then you could run an checks.each();
As a side not, do not give elements the same ID name or else JavaScript will not know which element you are trying to select. If you are going to select elements based on their id, make sure they have different ID's.

JavaScript unsure how to get querySelectorAll() to connect to div class? [duplicate]

When I click on the checkbox at the top, it puts a '0' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop. One of the elements in html looks like this.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
box.dataset.price = totalprice + box.dataset.price;
} //if
} //for
document.getElementsByName("total")[0].value = totalprice;
}
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input type="checkbox" name="event[]" value="11" data-price="35.00"></span>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
You have no total in the code you provided.
I would personally use ID when only having one element and if more, use relative addressing and/or delegation
const form = document.getElementById('booking');
const total = document.getElementById('total');
document.getElementById("booking").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="booking" method="get">
<section id="book">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
</div>
<div class="item">
<span class="eventTitle">Ash</span>
<span class="eventStartDate">202</span>
<span class="eventEnd">2020-12-31</span>
<span class="catD">Exhib</span>
<span class="venueNa">The Biy</span>
<span class="eventPr">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
</div>
</section>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
</form>

Button Changes the Final Cost/Value

I've created few buttons, and when clicked I want to affect the final cost, working but not as it should be. The button has a value and the final value of cost doesn't work, can someone let me know what I'm doing wrong?
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].click) {
total += parseFloat(input[i].value);
}
}
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
But when I pick one, the final price won't work perfectly. is displaying a different number! can some help me?
Attach the click event to all the buttons and add the cost on every click like the snippet below shows.
NOTE : If you want to add the cost just one time by button you could disable the button immediately after the click using :
this.setAttribute('disabled','disabled');
Hope this helps.
var products = document.querySelectorAll(".buttonBg");
for (var i = 0; i < products.length; i++) {
products[i].addEventListener("click", totalIt);
}
function totalIt() {
var total = document.querySelector("#total");
var currentVal = parseInt( total.innerText );
var new_val = parseInt( this.value );
if( this.classList.contains('clicked') ){
total.innerText = ( currentVal - new_val ).toFixed(2);
}else{
total.innerText = ( currentVal + new_val ).toFixed(2);
}
document.querySelector("#total2").innerText = total.innerText;
this.classList.toggle('clicked');
}
.clicked{
color: green;
}
<div class="priceWrapper">
<h3 class="priceText1">$<span id="total">0.00</span></h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" name="product" value="25.00" type="button">Producto 3</button>
</label>
<label>
<button class="buttonBg" name="product" value="10.00" type="button">Producto 4</button>
</label>
</form>
</div>
<h3 class="priceText1">$<span id="total2">0.00</span></h3>
I have adapted your code to make this work see below
Note below i have added id's to the product buttons.
<div class="priceWrapper">
<h3 class="priceText1" id="total">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
<div class="item">
<div class="itemProduct">
<h4 class="itemText">
<span class="no_selection">Logos</span>
</h4>
</div>
<div class="itemHidden">
<form action="" id="theForm">
<label>
<button class="buttonBg" id="product1" name="product" value="25.00" type="button">
Producto 3
</button>
</label>
<label>
<button class="buttonBg" id="product2" name="product" value="10.00" type="button">
Producto 4
</button>
</label>
</form>
</div>
Then i have modified your code
//
// this will be the element clicked so just add it, as below
//
function addProduct() {
el = this;
total += parseFloat(el.value);
total_el.innerText = "$" + total.toFixed(2);
};
//
// Cache your total get a reference to the total element (faster!)
// when you write your code don't keep doing stuff when it can be done
// once - speed is everything and as you write more complex stuff
// doing it write from day one will pay off in your work (toptip)
//
var total = 0;
var total_el = document.querySelector(".priceText1");
//
// Bind up the click event
//
document.getElementById('product1').onclick = addProduct;
document.getElementById('product2').onclick = addProduct;
And here you can see the end result
https://jsfiddle.net/64v3n1se/
To scale this you would add the click handler using a class and a loop but for simpleness i have... kept it simple.
Because during your calculation you are getting all button's values and add them up so whenever the button is clicked you calculate the sum of the values of the buttons.
Your way of thinking right now, as far as I can tell, is wrong.
You can change your html code and script code like this.
With this way we are passing object of button to the function and we increase the global total variable within the function. Later on you change the dom.
var total = 0;
function totalIt(obj) {
total = total + parseFloat(obj.value);
document.querySelector(".priceText1").innerText = "$" + total.toFixed();
}
And pass the object of button in the html with
<button class="buttonBg" name="product" value="10.00" type="button" onclick="totalIt(this)">

How to compute a total using 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!

Categories