Why is output only showing on 2 of my input boxes? - javascript

Trying to learn JQUERY/HTML, so I am making a shopping cart. I am trying to output subtotal, tax, shipping, and total cost to input boxes. The first 2, sub total and shipping cost show, but nothing is outputted for the last 2 input boxes.
HTML
<div class="form-group">
<div class="subTotal">
<label for="subtotal"><span>Sub Total</span><span>*</span><input type="number" class="input-field" name="subtotal" id="subtotal" disabled/></label>
<label for="shipping"><span>Shipping</span><span>*</span><input type="number" class="input-field" name="shipping" id="shipping" disabled/></label>
<label for="tax"><span>Tax</span><span>*</span><input type="number" class="input-field" name="tax" id="taxCost" disabled/></label>
<label for="total"><span>Total</span><span>*</span><input type="number" class="input-field" name="total" id="total" disabled/></label>
</div>
</div>
JS
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".cost").each(function () {
var value = $(this).text();
// add only if the value is number
if (!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
var subtotal = sum;
var shippingCost = (sum * 0.085);
var tax = (((sum + shipping) * 0.11));
var total = (sum + shippingCost + tax);
$("#subtotal").val(subtotal);
$("#shipping").val(shippingCost);
$("#taxCost").val(tax);
$("#total").val(total);
};

Are you sure this isn't a typo?
var tax = (((sum + shipping) * 0.11));
Shouldn't it be
var tax = (((sum + shippingCost) * 0.11));

Alright so I tried to understand your code, first off I could not find .cost anywhere in the code so the output was 0 from the start, so I added a value to the inputs and then this.
This code block was your original code, the shipping variable is named wrongly, it's probably supposed to be shippingCost.
var tax = ((sum + shipping) * 0.11);
Here is the code.
https://jsfiddle.net/dbu41wpa/2/

Related

Using JS to show HTML output of calculation

I am trying to build a calorie calculator using HTML and JS and am currently struggling to show the output on screen (or via console.log). I know I'm doing something very basic quite wrong but can't currently pinpoint what that is.
Here's both my HTML and JS code below:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
function calcBMR(gender, weightKG, heightCM, age) {
// Calculate BMR
if (gender = 'male') {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Several things need to be modified in order to achieve your desired result.
The line document.getElementById("bmrForm").addEventListener("submit", calcBMR); is not needed because we can pass in a function directly to the onsubmit attribute of the form element.
The gender, weightKG, heightCM, and age parameters are not automatically passed in to the calcBMR function. The values need to be retrieved from the document.
The BMR variable needs to be defined above the if/else block because of scoping.
A return statement needs to be added to the onsubmit attribute so that the form does not submit and refresh the page. Alternatively, if the desired effect is to update the text on the screen, a button element with a click event handler added to it may be a better option that a form with a submit handler.
Strings are compared using == or === in JavaScript. Therefore, the gender = 'male' part needs to be changed to gender === 'male'.
In order to update the output, the element's textContent can be changed with document.getElementById("output").textContent = BMR.
Below is the code with the changes listed above.
function calcBMR() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let BMR;
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
document.getElementById("output").textContent = BMR;
return false;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="return calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
First, you are using a button with a type="submit", which is used to submit form data to a resource that will receive it and process it. In this case, you probably just want a button with type="button" that will only do what you've configured it to do (show the results on the screen).
After making that change, you should populate a pre-existing, but empty element with the result.
But you do have an issue with how and where you are declaring BMR. The let declaration should be outside of the if/then code but inside the function so it has scope throughout the function.
Also, your button's id is incorrect in the event handler setup.
Next, any value that you get from an HTML element will be a string and if you intend to do math with that value, you'll need to convert it to a JavaScript number. There are several ways to do this, but one shorthand way is to prepend the value with a + as you'll see I've done below.
Also, if someone were to type Male into the gender textbox, your code would not process it as a male because your code only checks for male, not Male. By forcing the input to lower case, your code will work (provided they spell male correctly). Preferably, you'd use a set of radio buttons or a drop down list for the user to choose from.
And, in conjunction with that, JavaScript uses = for assigning a value, not comparison. For loose equality (automatic type conversion) use == and for strict equality (no type conversion), use ===.
let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");
// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
function calcBMR(gender, weightKG, heightCM, age) {
let BMR = null; // Declare the variable in the function scope
console.log(gender, weightKG, heightCM, age);
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="button" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Working Codepen
There are a few fundamental flaws in your code. Having said that, studying this will really give you a proper understanding of Javascript.
HTML:
<body>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?" name="gender">
<input type="number" id="weight" placeholder="Weight in KG" name="weight">
<input type="number" id="height" placeholder="Height in CM" name="height">
<input type="number" id="age" placeholder="How old are you?" name="age">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Javascript:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
function calcBMR(e) {
e.preventDefault();
output.innerText = ''
const formData = new FormData(e.target)
const { age, gender, height, weight} = Object.fromEntries(formData);
let BMR = 0
// Calculate BMR
if (gender === 'male') {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
} else {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
}
output.innerText = BMR
}
You can remove the line document.getElementById("bmrForm").addEventListener("submit", calcBMR);
You can pass event to onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">
function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
The BMR is in the if tree, it must be in parent.
Try this!
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.getElementById('output');
function calcBMR(event) {
// Get the [gender, weightKG, heightCM, age] value
let gender = document.getElementById('gender').value;
let weightKG = document.getElementById('weight').value;
let heightCM = document.getElementById('height').value;
let age = document.getElementById('age').value;
// Set default BMR to 0
let BMR = 0;
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.innerText = BMR;
// Cancel form submit
event.preventDefault();
return;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
I used a selector instead of the text field for the gender.
I used form.elements to get the values from the form.
I used event.preventDefault(); to prevent the form from redirecting on submit.
// your form
var form = document.getElementById("formId");
var DoMagic = function(event)
{
event.preventDefault();
var elements = form.elements;
if (elements["gender"].value == "male")
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
}
else
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
}
document.getElementById("result").textContent = "Result: " + result;
}
// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
<label>Gender</label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label>Weight (kg)</label>
<input name="weight" type="number">
<br>
<label>Height (cm)</label>
<input name="height" type="number">
<br>
<label>Age (years)</label>
<input name="age" type="number">
<br>
<input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>
Try this one, you are almost done, just by getting value from the input when user clicks the button.
But I have to notice you that submit button will immediately redirect to a new page, you should use click instead if you want to show yourself result.
document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
let weight = document.querySelector('#weight').value
let height = document.querySelector('#height').value
let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
function calcBMR(gender, weightKG, heightCM, age) {
let BMR
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
document.querySelector('#output').textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>

JavaScript array application

I'm trying to create a sample accounting system, the checkbox can be add to the total after it's checked and the input text is the amount of the money.
but my result keep getting zero, I can't figure it out.
Anyone can help me handle this problem?
I've test that the length of total_ary is 0, I think that is the mainly problem
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount").value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You do
document.getElementsByName("amount").value
but getElementsByName returns a collection, not an element.
You do
var total_ary = [];
// ... code that doesn't reference total_ary
for (i = 0; i < total_ary.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
But since the code in between doesn't reference total_ary, the total ends up being 0.
From a selected checkbox, you need to navigate to the associated input:
document.getElementsByName("amount")[i].value
since i is the cb index you're iterating over, the same i in the amount collection will refer to the input you need.
Or, more elegantly, just navigate to the next element in the DOM when a checkbox is checked, and take the number for each product's price from the DOM too. You can also select only the checked checkboxes immediately with a :checked selector, and attach the event listener using addEventListener (instead of an inline handler; inline handlers should be avoided)
document.querySelector('button').addEventListener('click', () => {
let total = 0;
for (const input of document.querySelectorAll('[name=cb]:checked')) {
const price = input.nextSibling.textContent.match(/\d+/)[0];
const amount = input.nextElementSibling.value;
total += price * amount;
}
document.getElementById("result").innerHTML = total + "元";
});
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input><br>
<input type="checkbox" name="cb" checked>$20:<input><br>
<input type="checkbox" name="cb" checked>$30:<input><br>
</fieldset>
<button>Count</button>
<p>Total = <span id="result">
document.getElementsByName() returns a collection of elements. so calling value property will not work there as it does not have such property.
You can hold input elements with amount_inputs variable and iterate over it (in the example below by using spread syntax and Array.reduce())
And with Array.reduce() you can calculate the sum of the prices. There is no need for var amount = [] and var total_ary = [] variables.
Hope this helps
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount_inputs = document.getElementsByName("amount")
var total = 0;
var price = [10, 20, 30];
total = [...input_cb].reduce((total, cb, i) => {
if(cb.checked){
total += (parseInt(amount_inputs[i].value) || 0) * price[i]
// ^^^^^^^^^ This is to avoid NaN multiplication
}
return total
},0);
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Use Index while retrieving the element from document.getElementsByName("amount");
Use for loop on amount array not on total_ary
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10, 20, 30];
var i = 0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked) {
amount.push(document.getElementsByName("amount")[i].value); //get amounts of the products
} else {
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += isNaN(parseInt(total_ary[i])) ? 0 : parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = "$" + total ;
}
<fieldset>
<input type="checkbox" name="cb" checked>$10:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$20:<input type="text" name="amount"><br>
<input type="checkbox" name="cb" checked>$30:<input type="text" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
You have made a few mistakes:
(1) If you want to keep all the checkboxes checked at initial stage
use checked="true" in place of checked
(2) getElementsByName("amount") returns an array, so you should use the index as well
(3) total_ary length is 0 initially.. therefore, you should run the loop with input_cb. (Here, you can do both the task with a single loop: refer code below)
Refer the code with corrections:
<!DOCTYPE html>
<html>
<head>Order sys
<script>
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amount = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked){
amount.push(parseInt(document.getElementsByName("amount")[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
total += parseInt(amount[i] * price[i]) //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
</script>
</head>
<body>
<fieldset>
<input type = "checkbox" name="cb" checked="true">$10:<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked="true">$20:<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked="true">$30:<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
</body>
</html>
You can refactor your code:
Fist use inputs of type number <input type="number" name="amount"> to accept only numbers from your end users
Then, you can work with indexed arrays like [...document.querySelectorAll('input[name="cb"]')] and loop only one time with Array.prototype.reduce() to get the total
Code example:
function Totalamount() {
const inputNumberArr = [...document.querySelectorAll('input[name="cb"]')]
const inputAmountArr = [...document.querySelectorAll('input[name="amount"]')]
const priceArr = [10, 20, 30]
const total = inputNumberArr.reduce((a, c, i) => {
const num = c.checked ? +inputAmountArr[i].value : 0
return a + num * priceArr[i]
}, 0)
document.getElementById('result').innerHTML = '$' + 0
document.getElementById('result').innerHTML = '$' + total
}
<fieldset>
<input type="checkbox" name="cb" checked> $10:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $20:
<input type="number" name="amount"><br>
<input type="checkbox" name="cb" checked> $30:
<input type="number" name="amount"><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">
Is this what you are looking for?
Errors that I identified.
Making use of document.getElementsByName("amount").value instead of making the respective amount field you were making use of the global selector.
Trying to loop total_ary array instead of amount array.
function Totalamount() {
var input_cb = document.getElementsByName('cb');
var amountInput = document.getElementsByName('amount');
var amount = [];
var total_ary = [];
var total = 0;
var price = [10,20,30];
var i=0;
for (i = 0; i < input_cb.length; i++) {
if (input_cb[i].checked && amountInput[i].value){
amount.push(parseInt(amountInput[i].value)); //get amounts of the products
}
else{
amount.push(0); //If there is no input, add 0 to the array
}
}
for (i = 0; i < amount.length; i++) {
total_ary.push(parseInt(amount[i] * price[i])); // Add the products' total price to array
total += parseInt(total_ary[i]); //Counting the total money
}
document.getElementById("result").innerHTML = "$" + 0;
document.getElementById("result").innerHTML = total + "元";
}
<fieldset>
<input type = "checkbox" name="cb" checked>$10
<input type="text" id="amount_milk" name="amount" ><br>
<input type = "checkbox" name="cb" checked>$20
<input type="text" id="amount_soymlik" name="amount"><br>
<input type = "checkbox" name="cb" checked>$30
<input type="text" id="amount_blacktea" name="amount" ><br>
</fieldset>
<button onclick="Totalamount()">Count</button>
<p>Total = <span id="result">

Modificate in live value of a input

I have a form conversion, and I need the result is updated according to the amount entered by the user in live.
But the result is always the same.
I think the problem is in the variable price, this is not updated with the last written number of input.
This is the form
<input type="text" id="from_amount" value="0" name="amount" />
<span class="num" id="conv_result">0</span>
<input type="submit" action="" method="" >
This is the javascript
function a(){
var price = $("#from_amount").val(); //Get the number of the input
if (price == 0){
var total = 1;
}else if (price > 20 && price < 30){
var total = price * 2;
}else{
var total = 4;
}
return total;
}
var conver = {
'people': {
'rooms': a()
},
};

Get array textfield and calculate javascript

forexample, i have this code (results from a php script loop):
<input type="text" name="qtty[]" id="qtty[]" onFocus="startCalc();" onblur="stopCalc();">
<input type="hidden" name="price[]" id="price[]">
<input type="text" name="totalprice[]" id="totalprice[]">
And this for javascript:
function startCalc(){
interval = setInterval("calc()",500);
}
function calc(){
$('input[name="qtty[]"]').each(function(){
qtty = $(this).val();
});
$('input[name="price[]"]').each(function(){
price = $(this).val();
});
total = (qtty * 1) * (price * 1);
$('input[name="totalprice[]"]').val(total);
}
function stopCalc(){
clearInterval(interval);
}
The moment I enter the first input to the array, the program does not show anything. but at the time of the second array of data fed, TotalPrice will change both
Here, Example pict:
http://s7.postimg.org/memsupuh7/Capture1.png
http://s23.postimg.org/6rdfk2rzf/Capture.png
I think you are in the wrong way. This is more preferred variant:
<input type="text" name="qtty">
<input type="hidden" name="price" value="2">
<input type="text" name="totalprice">
<br>
<input type="text" name="qtty">
<input type="hidden" name="price" value="3">
<input type="text" name="totalprice">
and
$('input[name="qtty"]').keyup(function() {
var qtty = $(this).val();
var price = $(this).next().val();
var total = (qtty * 1) * (price * 1);
$(this).nextAll().eq(1).val(total);
});
fiddle
try this
Assign the default value initially
var qtty=0;
var price =0;
var interval ;
function startCalc(){
interval = setInterval(calc,500);
}
function calc(){
$('input[name="qtty[]"]').each(function(){
qtty = $(this).val();
});
$('input[name="price[]"]').each(function(){
price = $(this).val();
});
total = (qtty * 1) * (price * 1);
$('input[name="totalprice[]"]').val(total);
}
function stopCalc(){
clearInterval(interval);
}

Calculating totals when clicking checkboxes

I have a list of radio buttons represented by this code:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
Whenever a button is selected I need the subtotal and total to be updated.
This is how i want it to look.
Subtotal: <br />
Tax:<br />
Total:<br />
Where tax is always %7 or .7
The prices of menu 1 through 7 increments by $5. Menu1 is $5, menu2 is $10 and so forth.
I was trying to figure out the JavaScript to this but the problem is that i don't want it to display right after the buttons I want it displayed on the bottom of the page.
If I do document.write the whole page gets overwritten. Please help me on this issue guys. I am sure it's really simple.
Preamble
This sounds like homework to me. However, I find that the best way to learn, is by example.
So here's me, leading by example, OK?
You didn't give me much to go on, so for the sake of this example, I'm assuming you've got a list of checkboxes or radiobuttons that say Menu 1... Menu n. Each checkbox that is checked will be added to the subtotal, and then the tax calculated on top of that.
Doing it with radio buttons is a little easier, so I added that example as well.
On the bottom of the post are references for future study on what is used in this example.
If you have any further questions please ask them in the comment area at the bottom of this post.
The Javascript (checkboxes) | JSFiddle example (see it in action)
//Set the tax and base cost
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_checkboxes = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_checkboxes.length; i++){
e_checkboxes[i].onchange = function(){
//Recalculate subtotal
get_subtotal();
}
}
//get_subtotal calculates the subtotal based on which checkboxes are checked
function get_subtotal(){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
for(var i = 1; i <= e_checkboxes.length; i++){
//If the checkbox is checked, add it to the total
if(e_checkboxes[i-1].checked){
f_sub_total += i * i_menu_base;
}
}
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the display element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
The Javascript (radio buttons) | JSFiddle example (see it in action)
//Set the tax
var f_tax = 0.07,
i_menu_base = 5;
//Declare all the variables that will be used
var e_menu = document.getElementById("menu"),
e_radios = e_menu.getElementsByTagName("input"),
e_subtotal = document.getElementById("sub_total");
// Add event listeners for when any checkbox changes value
for(var i = 0; i < e_radios.length; i++){
e_radios[i].onchange = function(){
//Recalculate subtotal
get_subtotal(this);
}
}
//get_index gets the index of the element (1..n)
function get_index(element){
for(var i = 1; i <= e_radios.length; i++){
if(e_radios[i-1] == element){
return i;
}
}
}
//get_subtotal calculates the subtotal based on the radio that was changed
function get_subtotal(el){
var f_sub_total = 0.0,
f_grand_total = 0.0;
var subtotal, tax, grandtotal;
f_sub_total += get_index(el) * i_menu_base
//Calculate the grand total
f_grand_total = f_sub_total*(1+f_tax);
//Format them
subtotal = (Math.round(f_sub_total*100)/100).toFixed(2);
tax = (Math.round(f_tax*10000)/100).toFixed(2);
grandtotal = (Math.round(f_grand_total*100)/100).toFixed(2);
//Add them to the element
e_subtotal.innerHTML = "Subtotal: "+subtotal+"<br />";
e_subtotal.innerHTML += "Tax: "+tax+"%<br />";
e_subtotal.innerHTML += "Total: "+grandtotal;
}
References for future study
In order in which they appear
getElementById()
getElementsByTagName()
looping through an array
onchange
Math.round(), decimal trick and toFixed()
innerHTML
Despite any additonal input from you, and my better judgement, I was bored so I did it all.
HTML:
<form id="menu4strombolis">input1
<input type="radio" name="menu1" value="5">
<br>input2
<input type="radio" name="menu2" value="10">
<br>input3
<input type="radio" name="menu3" value="15">
<br>input4
<input type="radio" name="menu4" value="20">
<br>input5
<input type="radio" name="menu5" value="25">
<br>input6
<input type="radio" name="menu6" value="30">
<br>input7
<input type="radio" name="menu7" value="35">
<br>
</form>
<button id="getTotal">Total</button>
<div id="subtotal">Sub-Total:</div>
<div id="tax">Tax:</div>
<div id="total">Total:</div>
JS:
var button = document.getElementById("getTotal");
button.onclick = function () {
var subtotalField = document.getElementById("subtotal");
var radios = document.forms["menu4strombolis"].getElementsByTagName("input");
var subtotal = 0;
var tax = 0;
var total = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
subtotal += parseInt(radios[i].value);
}
}
tax = (subtotal * .07).toFixed(2); ;
total = subtotal + tax;
document.getElementById("subtotal").innerHTML = "Sub-Total: $" + subtotal;
document.getElementById("tax").innerHTML = "Tax: $" + tax;
document.getElementById("total").innerHTML = "Total: $" + total;
};
and the working fiddle:
http://jsfiddle.net/RGvTt/1/
Though on a side note, you should either group some of the radios together in the same group... or make them checkboxs.
Updated to fix the bug that the OP couldn't fix:
http://jsfiddle.net/RGvTt/4/
Need to use parseFloat.
iPhone fiddle programming FTW!
What you want is element.innerHTML
So it would look something like this:
<form id="menu4strombolis">
input1 <input type="radio" name="menu1"><br />
input2 <input type="radio" name="menu2"><br />
input3 <input type="radio" name="menu3"><br />
input4 <input type="radio" name="menu4"><br />
input5 <input type="radio" name="menu5"><br />
input6 <input type="radio" name="menu6"><br />
input7 <input type="radio" name="menu7"><br />
</form>
..... ..html stuff here
Subtotal: <span id="subtotal"></span><br/>
Tax: <span id="tax"></span><br/>
Total: <span id="total"></span><br/>
ETC...
<script>
var subtotal = //whatever menu item is checked then .value();
var span_subtotal = document.getElementById("subtotal);
var tax = document.getElementById("tax");
var total = document.getElementById("total");
var the_tax = subtotal * .07;
span_subtotal.innerHTML = subtotal;
tax.innerHTML = the_tax;
total.innerHTML = subtotal + the_tax;
<script>

Categories

Resources