Confusion with Javascript variable scoping - javascript

I'm trying to create a simple test in JS. I have a function that creates 4 radio-buttons and add them to the html. When I call it n times, I just add the same 4 radio buttons to the div and when I try to select one answer from the 4th question for example it still selects the answer from the first div/question.
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
function test_2() {
var a = getRandom(0, 10) - 5;
while (a == 0)
a = getRandom(0, 10) - 5;
var b = getRandom(0, 10) - 5;
//create the div in which i add the radio buttons
var div = document.createElement('div');
div.setAttribute('class', 'parent');
div.setAttribute('id', '2');
document.body.appendChild(div);
//create the radio button and set its attributes
var radio1 = document.createElement('input');
var label1 = document.createElement('label');
label1.innerHTML = a * 4 + b;
label1.setAttribute('for', 'radio1');
radio1.setAttribute('type', 'radio');
radio1.setAttribute('value', a * 4 + b);
radio1.setAttribute('id', 'radio1');
radio1.setAttribute('name', 'answ');
radio1.innerHTML = a * 4 + b;
//add it to the div
div.appendChild(radio1);
div.appendChild(label1);
}
test_2();

The name attribute must be different for each question:
<form>
<!-- Question 01 -->
<fieldset id="group1">
<input type="radio" value="" name="group1">
<input type="radio" value="" name="group1">
</fieldset>
<fieldset id="group2">
<!-- Question 02 -->
<input type="radio" value="" name="group2">
<input type="radio" value="" name="group2">
<input type="radio" value="" name="group2">
</fieldset>
</form>

That's probably happening because every "radio button pack" test_2() is generating has the same name property value (answ).
A quick solution would be to send a name as a parameter to test2 so you "namespace" your radiobuttons like this:
function test_2(name) {
var a = getRandom(0, 10) - 5;
...
radio1.setAttribute('name', name + '-answ');
...
}
This way, if you're calling this function within a loop, you can pass in the index as the name parameter and ensure uniqueness of names.

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>

get the sum of two checkbox on check

hy, my is that it doesn't work. i want on check to visualize the sum between the selected checkbox. for example if i check only the first, it shows me a value, for the other one another value; if i check both, the sum of the values.
thanks for the help
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function setvalue(x){
if(x.checked){
x.value = x.defaultValue;
} else {
x.classList.value = 0;
}
return x.value;
}
var a = setvalue(document.getElementById("checkvalnotset1"));
var b = setvalue(document.getElementById("checkvalnotset2"));
var p = document.getElementById("sumvalnotset");
function sumvalnotset(){
p.innerHTML = "the value is " + +a + +b
}
</script>
</div>
var sum = 0;
function sumvalnotset(event) {
if(event.checked) {
sum = sum + parseInt(event.value);
} else {
sum = sum > 0 ? sum - parseInt(event.value) : sum;
}
document.getElementById('sumvalnotset').innerText = 'the value is: '+ sum;
}
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset(this)" onchange=""> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset(this)"> this is a checkbox that gain value when checked
<p id="sumvalnotset">
the value is: 0
</p>
</div>
You could rewrite your event handler has follows:
<div>
<input type="checkbox" id="checkvalnotset1" value="45" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<input type="checkbox" id="checkvalnotset2" value="20" onClick="sumvalnotset()"> this is a checkbox that gain value when checked
<p id="sumvalnotset">the value is 0</p>
<script>
function sumvalnotset() {
var chk1 = document.getElementById("checkvalnotset1");
var chk2 = document.getElementById("checkvalnotset2");
var val1 = chk1.checked ? Number(chk1.value):0;
var val2 = chk2.checked ? Number(chk2.value):0;
var p = document.getElementById("sumvalnotset");
p.innerHTML = "the value is " + (val1 + val2);
}
</script>
</div>

Subtract value multiple times in JS

I have two textbox's. Textbox one has the remaining hp that it gets from a variable. Textbox two has a button that when you click it, it runs dmgNPC and subtracts the damage that you enter into the textbox from the hp text box.
The question i have is how do i get JS to subtract from the new value that it shown in the remaining hp textbox?
var hp = 10;
function dmgNPC(hp) {
var damage = document.getElementById("damage").value;
var theDMG = hp - damage;
return document.getElementById("remaining").value = theDMG;
}
<label for="damage">Damage to NPC</label>
<input type="text" id="damage">
<button type="button" onclick="dmgNPC(hp);">Enter Damage</button>
<br/>
<label for="remaining">Remaining Health</label>
<input type="text" id="remaining">
I think you want something like this
var hp = 10;
function dmgNPC() {
var damage = document.getElementById("damage").value;
hp -= damage;
document.getElementById("remaining").value = hp;
}
<label for="damage">Damage to NPC</label>
<input type="text" id="damage">
<button type="button" onclick="dmgNPC();">Enter Damage</button>
<br/>
<label for="remaining">Remaining Health</label>
<input type="text" id="remaining">
Geoffrey let me see if I understand this. You want to subtract from 10 at the beginning but after that take from the remaining value so you can work your way down to 0 health? If so here is the JS I wrote for that.
var hp = 10;
function dmgNPC(hp) {
if(document.getElementById("remaining").value){
var damage = document.getElementById("damage").value;
var theDMG = document.getElementById("remaining").value - damage;
}else{
var damage = document.getElementById("damage").value;
var theDMG = hp - damage;
}
document.getElementById("remaining").value = theDMG;
}

Adding checkbox with multiple value

I have a set of books in checkboxes which a user can select. Every time a book is checked the price adds up. I also need to add its corresponding weight. I've modified this very useful example but to no avail.
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" data-toggle="checkbox"> Instagram
</label>
<label class="checkbox">
<input value="50" bweight=".4" type="checkbox" class="sum" data-toggle="checkbox"> Review site monitoring
</label>
<label class="checkbox">
<input value="30" bweight=".2" type="checkbox" class="sum" data-toggle="checkbox"> Google+
</label>
<label class="checkbox">
<input value="20" bweight=".6" type="checkbox" class="sum" data-toggle="checkbox"> LinkedIn
</label>
<div class="card-charge-info">
<span id="payment-total">0</span>
</div>
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
totwgt = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var add = this.value * (this.checked ? 1 : -1);
var add = this.wgt * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + add
totwgt.innerHTML = parseFloat(total1.innerHTML) + add
}
}
Heres the code https://jsfiddle.net/u8bsjegk/2/
There's several issues in your code. Firstly you define the add variable in two places, one for the value the other for weight so your calculation is broken from there. Also note that bweight is not a valid attribute on the input element. To add your own meta data you should use a data-* attribute instead.
Try this:
var inputs = document.getElementsByClassName('sum'),
totalValue = document.getElementById('payment-total'),
totalWeight = document.getElementById('payment-w');
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var value = parseFloat(this.value);
var weight = parseFloat(this.dataset.weight);
totalValue.innerHTML = parseFloat(totalValue.innerHTML) + value
totalWeight.innerHTML = parseFloat(totalWeight.innerHTML) + weight
}
}
As you've tagged this question with jQuery, here's a working implementation for that
var $inputs = $('.sum'),
$totalValue = $('#payment-total'),
$totalWeight = $('#payment-w');
$inputs.change(function() {
var value = parseFloat(this.value);
var weight = parseFloat($(this).data('weight'));
$totalValue.text(function(i, text) {
return parseFloat(text) + value;
});
$totalWeight.text(function(i, text) {
return parseFloat(text) + weight;
});
})
Working example
You have few issues:
You redeclare add variable
you have typo in total1 it should be totwgt
you don't have element with payment-w id
instead of this.wgt you should use this.getAttribute('bweight')
https://jsfiddle.net/u8bsjegk/6/

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