javascript autosum - javascript

Hi I am doing autosum in javascript which is working fine here in this link http://maatren.com/auto-sum.html but I want reverse autosum also.
Both are working fine but seperately. they are not working fine together.
I use this code
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
third = document.autoSumForm.thirdBox.value;
document.autoSumForm.thirdBox.value = (one * 1) + ((two / 100) * one);
//document.autoSumForm.firstBox.value = (third * 1) - ((two / 100) * third);
}
function stopCalc(){
clearInterval(interval);
}
My html is
<div style="width: 200px; text-align: center;">
<form name="autoSumForm">
<input class="right" type=text name="firstBox" value="" onFocus="startCalc();" onBlur="stopCalc();"><br>
% <input class="right" type=text name="secondBox" value="10" onFocus="startCalc();" onBlur="stopCalc();"><br>
= <input class="right" type=text name="thirdBox" value="" onFocus="startCalc();" onBlur="stopCalc();"><br>
</form>
</div>
The problem is that when i remove comment from third box then it tops working. I want autosum and reverse autosum both at same time.

<div style="width: 200px; text-align: center;">
<form name="autoSumForm">
<input class="right" type=text name="firstBox" value="" onkeyup="calc(1);"><br>
% <input class="right" type=text name="secondBox" value="10" onkeyup="calc(2);"><br>
= <input class="right" type=text name="thirdBox" value="" onkeyup="calc(3);"><br>
</form>
</div>
​
.
function calc(box){
one = document.autoSumForm.firstBox.value;
two = document.autoSumForm.secondBox.value;
third = document.autoSumForm.thirdBox.value;
if(box == 1){
document.autoSumForm.thirdBox.value = (one * 1) + ((two / 100) * one);;
}else if(box == 2 || box == 3){
document.autoSumForm.firstBox.value = (third * 1) - ((two / 100) * third);
}
}

Related

User friendly Order Form

Hello I am attempting to create a user friendly application that allows the user to buy pencils, pens, and erasers. A total cost should be displayed.
My code mostly works except for one problem. the numbers that the user inputs in the boxes (how many pens/pencils/erasers they would like to buy) are not being used by the code. if I add a value manually to the code it performs the calculation (<input type="number" value="3" placeholder="# of erasers" min="0" id="numOfErasers">) could somebody please help me with getting the calculation to use user inputted numbers?
here's my code (JavaScript/HTML):
<!DOCTYPE html>
<html>
<head>
<title> Pencils Pens Erasers </title>
<script>
//this is the function that calcultes the cost
function costCalculator () {
var total = penCost + pencilCost + eraserCost;
return total;
}
</script>
</head>
<body>
<form>
<!--this is the order form-->
<br>
<u><b>please indicate how many of each you wish to order:</b></u>
<br><br>
Pens:<input type="number" placeholder="# of pens" min="0" id="numOfPens">
Pencils:<input type="number" placeholder="# of pencils" min="0" id="numOfPencils">
Erasers:<input type="number" placeholder="# of erasers" min="0" id="numOfErasers">
<br><br>
please select which province you are ordering from:<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan </option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select>
</form>
<script>
//these are all my variables
var pens = document.getElementById("numOfPens").value
var pencils = document.getElementById("numOfPencils").value
var erasers = document.getElementById("numOfErasers").value
var penCost = 0.50 * pens
var pencilCost = 0.30 * pencils
var eraserCost = 1.00 * erasers
var province = document.getElementById("whichProvince").value
var totalCost = costCalculator()
//this code adds taxes and discount to the total price based on province
if (province == 1) {
totalCost = (5 / 100) * totalCost + totalCost;
} else if (province == 1 && totalCost>30) {
totalCost = totalCost-5
} else if (province == 2) {
totalCost = (5 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
} else if (province == 3) {
totalCost = (6 / 100) * totalCost + totalCost;
totalCost = totalCost + 2;
}
/* function test () {
window.alert(total)
}
*/
function test2 () {
window.alert(totalCost)
}
document.write ("<br>" + " The total cost of your purchase will be: " + "<b>" + totalCost + "</b>" + "<br>")
</script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p><p align=center>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator(); test2();" >
</p>
</body>
</html>
As said in the comments you need to get familiar with events (this is another good resouce). The example below is a minimal working example, you can use that as reference when creating mininal reproducible examples.
The main difference is that it uses a button at the end with onclick attribute calling the costCalculator function.
function costCalculator() {
var pensTotal = document.getElementById("numOfPens").value * 0.5;
var pencilsTotal = document.getElementById("numOfPencils").value * 0.3;
var erasersTotal = document.getElementById("numOfErasers").value;
var total = parseFloat(pensTotal + pencilsTotal + erasersTotal);
var province = document.getElementById("whichProvince").value;
if (province == 1) {
total = (5 / 100) * total + total;
if (total > 30) {
total -= 5;
}
} else if (province == 2) {
total = (5 / 100) * total + total;
total += 2;
} else if (province == 3) {
total = (6 / 100) * total + total;
total += 2;
}
document.getElementById("output").innerHTML = total;
}
<label for="numOfPens">Pens:</label>
<input type="number" placeholder="# of pens" min="0" id="numOfPens"><br/>
<label for="numOfPencils">Pencils:</label>
<input type="number" placeholder="# of pencils" min="0" id="numOfPencils"><br/>
<label for="numOfErasers">Erasers:</label>
<input type="number" placeholder="# of erasers" min="0" id="numOfErasers"><br/>
<label for="whichProvince">please select which province you are ordering from:</label>
<select name="Province" id="whichProvince">
<option value="1" id="SK"> Saskatchewan</option>
<option value="2" id="AB"> Alberta </option>
<option value="3" id="MB"> Manitoba </option>
</select><br/>
<input type="button" value="Submit" id="submitButton" onclick="costCalculator()">
<p id="output"></p>
I've done a few irrelevant changes to your code, I'll answer anything you need in the comments.

Why does form not reset (all fields and div of result) after click clear?

I want display div id="showResult" after click calculate button and clear all input and div id="showResult" after click clear button in a form. But clear button doesn't work after I click the button.
What's the problem? How can I solve this problem?
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
You needed to hide the div in the clearForm
Here is your code cleaned up based on the DRY principle (don't repeat yourself)
We could get rid of some testing if we could trust the browser to respect the type="number" which is fairly well supported
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
// the "number" fields will not allow other data than numbers
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161; // add 5 for male, subtract 161 if female
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById("do-form").reset();
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" name="gender" value="male" checked="checked">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
The result div can not auto hide, you need add code to hide it
document.getElementById('showResult').style.visibility = "hidden";
or
document.getElementById('showResult').style.display= "none";
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
//document.getElementById('showResult').style.visibility = "hidden";
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I took some time to improve your code. As given in other answers already. You need to set the display of your result html back to none.
window.onload = function BMR() {
// Init
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
// Click handler
calculate.addEventListener('click', toBmr);
function toBmr() {
// Init
// Very good practice to first declare your vars
// However include result as well here
// Remove select because it's not doing anything
var result = "";
var penalty = 0;
if (gender.value && weight.value && height.value && age.value && gender.checked) {
// When you have duplicate code, check the difference!
// Only the penalty given at the end is different!
if (gender.value == 'male') {
penalty = 5;
} else {
penalty = -161;
}
// Now we calculate with one formula
result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + penalty;
// Add to html
document.getElementById('result').innerHTML = Number(result).toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
};
function clearForm() {
// This resets the form fields
document.getElementById("do-form").reset();
// This remove result again
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>

How to make a complex formula working with keyup event

I am still new in coding. I have to make this formula working.
GPro = 31 * ((Cr / 8.4)-1.5) * (kA-0.2) * kG
It is an online calculator that must work automatically after input from the user (keyup event).
There are three formulas on the site - CrumPro, CrumPo and Gpro (see Codes below). First two are working just fine. However as soon as I add the third one (GPro) in the Script the other two just crashed and stop working. I do something wrong, but I can't understand what. Maybe I use wrong the Math.pow function... I need an expert advise... Or maybe a better code. As I said - the first two formulas worked fine as long the third one is not in the script.
Thanks in advance
Here are the codes:
// Get CrumPro
function getCrPro() {
var CrmgPro= parseFloat($('#demo3').val());
var CrumPro = CrmgPro / 0.05;
var CrPro = CrumPro.toFixed(2);
if (isNaN(CrPro)) CrPro = 0;
$('#demo5').val((CrPro));
}
$(document).ready(function() {
$('#demo3').keyup(function(event) {
getCrPro();
});
});
// Get CrumPo
function getCrPo() {
var CrmgPo = parseFloat($("#res1").val());
var CrumPo = CrmgPo / 0.05;
var CrPo = CrumPo.toFixed(2);
if (isNaN(CrPo)) CrPo = 0;
$('#res2').val((CrPo));
}
$(document).ready(function() {
$('#res1').keyup(function(event) {
getCrPo();
});
});
//get GPro
function getGPro () {
var Cr = parseFloat($("#demo3").val());
var Cru = Cr / 0.05;
var Cru2 = Cru.toFixed(2);
var Cr8 = Cru2 / 8.4;
var kCr = Math.pow (Cr8, -1,5);
var kA = parseFloat($("#demo1").val());
var kAP = Math.pow (kA, -0,2);
var kG = parseFloat($("#demo4").val());
var G = (31 * kCr * kAP * kG);
if (isNaN(G)) G = 0;
$('#demo6').val((G));
}
$(document).ready(function() {
$('#demo3').keyup(function(event) {
getGPro();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="demo1" type=“number” name="age" placeholder="age">
<label for="demo1">kA (age)</label>
<br />
<input id="demo2a" class="gender" type="radio" name="gender" value="0,742" onClick="document.getElementById('demo4').value=this.value">
<label for="demo2a">female</label>
<input type="radio" name="gender" id="demo2b" class="gender" value="1" onClick="document.getElementById('demo4').value=this.value">
<label for="demo2b">male</label>
<br />
<input id="demo4" type="text" name="kG" placeholder="kG" readonly="true" value="0">
<label for="demo4">kG</label>
<br />
<input id="demo3" type="number" name="Cr" placeholder="CrPro">
<label for="demo3">CrPro</label>
<br />
<input id="demo5" type="text" name="CrumPro" readonly="true" placeholder="=CrPro/0,01131222" value="0">
<label for="demo5"> CrumPro </label>
<br />
<input id="demo6" type="text" name="GPro" readonly="true" placeholder=" GPro = 31 * ((Cr / 8.4)^-1.5) * (kA^-0.2) * kG)">
<label for="demo6"> GPro </label>
<br />
<input id="res1" type="number" name="CrPo" placeholder="Crea (mg/dL)">
<label for="res1"> CrPo </label>
<br />
<input id="res2" type="text" name="CrumPo" readonly="true" value="0" placeholder="= CrPo/0.01131222">
<label for="res2">CrumPo</label>
<br />
<input id="res3" type="text" name="GPo" readonly="true" placeholder="GPo = 31 * ((Cr / 8.4)^-1.5) * (kA^-0.2) * kG)">
<label for="res3">GPo</label>
Just a typo; you missed semicolon in getGPro code:
var G = (31 * kCr * kAP * kG)
Must be:
var G = (31 * kCr * kAP * kG);
UPDATE:
Also the getGPro function definition has a typo. function must be in lowercase:
function getGPro ()
You're using var with a capital V in your getGPro function

Doing math with Time using js

I have the following code:
HTML:
<form onsubmit="return false;">
<div class="col-5">
<label>
Page Time
<input id="pageTime" name="pageTime" type="time" step="1" tabindex="9">
</label>
</div>
<div class="col-5">
<label>
Ack Time
<input id="ackTime" name="ackTime" type="time" step="1" tabindex="10">
</label>
</div>
<div class="col-5">
<label>
Arrival Time
<input id="arrivalTime" name="arrivalTime" type="time" step="1" tabindex="11">
</label>
</div>
<div class="col-5">
<label>
Start Replace / Root Cause Found
<input id="startReplace" name="startReplace" type="time" step="1" tabindex="12">
</label>
</div>
<div class="col-5">
<label>
Replaced / Repair Completed
<input id="replaced" name="replaced" type="time" step="1" tabindex="13">
</label>
</div>
<div class="col-4">
<label>
Engagement
<input type="text" id="engagement" name="engagement" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Arrival
<input type="text" id="arrival" name="arrival" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Investigation
<input type="text" id="investigation" name="investigation" value="" readonly="readonly" />
</label>
</div>
<div class="col-4">
<label>
Mitigate
<input type="text" id="mitigate" name="mitigate" value="" readonly="readonly" />
</label>
</div>
<div class="col-1" style="text-align: center">
<label>
Total Ops Phases
<input type="text" name="totalOpsPhases" id="totalOpsPhases" value="" readonly="readonly" />
</label>
</div>
<div class="col-submit">
<button class="submitbtn" tabindex="14" onclick="opsTime();">Do the Math</button>
</div>
</form>
JS:
function toSeconds(time_str) {
// Extract hours, minutes and seconds
var parts = time_str.split(':');
var sum = 0;
// compute and return total seconds
for (c = 0; c <= 2; c++) {
if (c === 0) {
sum += parts[0] * 3600;
} else if (c === 1) {
sum += parts[1] * 60;
} else if (c === 2) {
if (parts[2] !== 'undefined') {
sum += parts[2];
}
}
}
return sum;
}
function opsTime() {
var time = [document.getElementById('pageTime').value, document.getElementById('ackTime').value, document.getElementById('arrivalTime').value, document.getElementById('startReplace').value, document.getElementById('replaced').value];
// Created an array to easily do the math :)
// Array mapping:
// 0 = pageTime
// 1 = ackTime
// 2 = arrivalTime
// 3 = startReplaceTime
// 4 = replacedTime
for (i = 0; i <= 4; i++) {
if (i === 4) {
var start = time[0];
var end = time[4];
} else {
start = time[i];
end = time[i + 1];
}
var startSec = toSeconds(start);
var endSec = toSeconds(end);
var difference = Math.abs(endSec - startSec);
// format time differnece
var result = [
Math.floor(difference / 3600), // an hour has 3600 seconds
Math.floor((difference % 3600) / 60), // a minute has 60 seconds
difference % 60
];
// 0 padding and concatation
result = result.map(function (v) {
return v < 10 ? '0' + v : v;
}).join(':');
var res = [];
res[i] = result;
}
document.getElementById('engagement').value = res[0];
document.getElementById('arrival').value = res[1];
document.getElementById('investigation').value = res[2];
document.getElementById('mitigate').value = res[3];
document.getElementById('totalOpsPhase').value = res[4];
}
What I'm trying to do is to pick the times filled in the inputs and show the difference in the inputs boxes below.
Engagement should be the time difference between Page Time and Ack Time;
Arrival should be the time difference between Ack Time and Arrival Time;
Investigation should be the time difference between Arrival and Start Replace Time;
Mitigate should be the time difference between Start Replace and Replaced time;
Total Ops Phases should be the time difference between Replaced and Page time.
I'm stuck on the code above for almost 8 hours, changed a lot of things trying to do the math and put each time difference inside an array and then use it to fill the inputs, but it seems the array isn't get filled with data.
Unfortunately I have to use the seconds as well, and I couldn't find much material with different solutions to calculate the difference of times using it.
I will be glad if someone can see another way to solve this matter.
Thanks in advance!
PS: Tried to insert a print of the form but I don't have the reputation needed.
The type="time" attribute is only supported by chrome, not Firefox or Internet Explorer so you should be using a compatibility library like these or one of your own making. If you just want to use chrome you can use valueAsNumber:
v.valueAsNumber
56013000
v.valueAsDate
Thu Jan 01 1970 10:33:33 GMT-0500 (EST)
v.value
"15:33:33"
Note that the Chrome console will show you these options with auto suggest.
Also jsfiddle

How to make different calculations based on the same radio button values?

I'm a novice. I've made a code based on this post:
SUM radio button values and checkboxes values in one calculation - javascript and html
I've made two groups of radio buttons with the values 1-5 (first group), and 100-500 (second group).
I need the value of the selected button from each groups to make different calculations with them and display the results.
Here I've multiplied the value of the first group with 2 and added the value of the second group. Now I want to display the result of an other calculation. For example:
var sum=parseInt(val1-3) + parseInt(val2*4)
How can I display both the results at the same time in separate "cells".
<form name="form1" id="form1" runat="server">
<legend>Header 1</legend>
<p><input id="rdo_1" type="radio" value="1" name="price" onClick="DisplayPrice(this.value);"><label for="radio1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="2" name="price" onClick="DisplayPrice(this.value);"><label for="radio2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="3" name="price" onClick="DisplayPrice(this.value);"><label for="radio3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="4" name="price" onClick="DisplayPrice(this.value);"><label for="radio4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="5" name="price" onClick="DisplayPrice(this.value);"><label for="radio5">Radio 5</label></p>
</form>
<hr>
<form name="form2" id="form2" runat="server">
<legend>Header 2</legend>
<p><input id="rdo_1" type="radio" value="100" name="price2" onClick="DisplayPrice(this.value);"><label for="rad1">Radio 1</label></p>
<p><input id="rdo_2" type="radio" value="200" name="price2" onClick="DisplayPrice(this.value);"><label for="rad2">Radio 2</label></p>
<p><input id="rdo_3" type="radio" value="300" name="price2" onClick="DisplayPrice(this.value);"><label for="rad3">Radio 3</label></p>
<p><input id="rdo_4" type="radio" value="400" name="price2" onClick="DisplayPrice(this.value);"><label for="rad4">Radio 4</label></p>
<p><input id="rdo_5" type="radio" value="500" name="price2" onClick="DisplayPrice(this.value);"><label for="rad5">Radio 5</label></p>
</form>
<p><label for="valueTotal">Value$:</label>
<input type="text" name="valueTotal" id="valueTotal" value="" size="2"readonly="readonly"> </p>
<script type="text/javascript">
function DisplayPrice(price)
{
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ )
{
if( document.form1.price[i].checked == true )
{
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ )
{
if( document.form2.price2[i].checked == true )
{
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1*2) + parseInt(val2);
document.getElementById('valueTotal').value=sum;
}
</script>
Simply define different input fields for your results.
<p>
<label for="valueTotal1">Value1$:</label>
<input type="text" name="valueTotal1" id="valueTotal1"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal2">Value2$:</label>
<input type="text" name="valueTotal2" id="valueTotal2"
value="" size="2" readonly="readonly" />
</p>
<p>
<label for="valueTotal3">Value3$:</label>
<input type="text" name="valueTotal3" id="valueTotal3"
value="" size="2" readonly="readonly" />
</p>
function DisplayPrice() {
for (i = 0; i < document.form1.price.length; i++) {
if (document.form1.price[i].checked == true) {
val1 = document.form1.price[i].value;
}
}
for (i = 0; i < document.form2.price2.length; i++) {
if (document.form2.price2[i].checked == true) {
val2 = document.form2.price2[i].value;
}
}
if (val1 != null && val2 != null) {
document.getElementById('valueTotal1').value = parseInt(val1) * 2 + parseInt(val2);
document.getElementById('valueTotal2').value = parseInt(val1) * 3 + parseInt(val2);
document.getElementById('valueTotal3').value = parseInt(val1) * 4 + parseInt(val2);
}
}
If you are allowed to use jQuery, you could simplyfy the function:
function DisplayPrice() {
var val1 = $('input[name=price]:radio:checked').val();
var val2 = $('input[name=price2]:radio:checked').val();
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}
I created two fiddles: with jQuery and without
Please note one other thing: Don't write parseInt(val1-3). You can't subtract 3 before the string is converted to an integer.
Edit
If you want to have default values, you can write them into the variables before searching for the checked radio button. If no checked button in found, the default value will stay the same. An other solution would be to check whether the variable is still empty and fill it with the default value after searching for the checked button.
function DisplayPrice() {
//Default values - solution I
var val1 = 1;
var val2 = 1;
val1 = $('input[name=price]:radio:checked').val();
val2 = $('input[name=price2]:radio:checked').val();
//Default values - solution II
if(val1 == null) {
val1 = 1;
}
if(val2 == null) {
val2 = 1;
}
if(val1 != null && val2 != null) {
$('#valueTotal1').val(parseInt(val1) * 2 + parseInt(val2));
$('#valueTotal2').val(parseInt(val1) * 3 + parseInt(val2));
$('#valueTotal3').val(parseInt(val1) * 4 + parseInt(val2));
}
}

Categories

Resources