How to get sum of onload inputs - javascript

HTML:
<table id="tab1">
<tr id="maint">
<td style="background-color:white;"></td>
<td>słowo klucz</td>
<td>ilość wynikow google</td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value="" required></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
<tr>
<td id="maint">słowo klucz</td>
<td><input type="text" name="klucz" value=""></td>
<td><input type="number" name="wyszkiwania" value="" onblur="sumX()" onkeyup="operatorf()" id="eq"required></td>
</tr>
</table>
JS:
var wejscie = document.getElementById('eq').value;
if ( wejscie <= 100000) {
var stawka13 = 59;
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
else {
var stawka13 = wejscie/100000*59;
if (stawka13 > 210) {
stawka13 = 210;
}
var stawka46 = stawka13*0.75;
var stawka710 = stawka46*0.55;
}
stawka13 = Math.round(stawka13).toFixed(2);
stawka46 = Math.round(stawka46).toFixed(2);
stawka710 = Math.round(stawka710).toFixed(2);
document.getElementById('sum13').innerHTML = "";
document.getElementById('sum46').innerHTML = "";
document.getElementById('sum710').innerHTML = "";
document.getElementById('sum13').innerHTML = " "+sum13+" zł";
document.getElementById('sum46').innerHTML = " "+sum46+" zł";
document.getElementById('sum710').innerHTML = " "+sum710+" zł";
I would like to get an sum of it but with this eq.
I try arr etc but aint work "properly" as I want.
My target is just sum all of it with all math in it.
I'm not allowed to add jq to it so it is impotant to stay on meta.

Related

Multiple calculations in html / javascript code - text box data entry

I have asked this question before but have had to clean it up, difficult to follow, cause it was a mess, so its down to the bone now, in the format below the code works, the issue I am having is that I want to add a second and third equation using the same variables, possibly a forth, I thought I could just add another equation in the same format below and would work (different ID), but its not, it calculates one and not the other, its for a stand alone computer, no internet, can't use any plugins either, been at it a while now and its annoying me but I am determined to get it to work. Its google chrome being used. Is this possible, any one help please. I have set the code back to calculating just the one equation.
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script type="text/javascript">
window.onload = function() {
CMCObj = document.getElementById('txtCMC');
WaterObj = document.getElementById('txtWater');
GlycerolObj = document.getElementById('txtGlycerol');
FlowObj = document.getElementById('txtFlow');
FreshObj = document.getElementById('tdFresh');
document.getElementById('btnReset').onclick = resetInputs;
document.getElementById('btnCalc').onclick = calcAddition;
};
function resetInputs() {
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
}
function calcAddition() {
var CMC = new Number(CMCObj.value);
var Water = new Number(WaterObj.value);
var Glycerol = new Number(GlycerolObj.value);
var Flow = new Number(FlowObj.value);
FreshObj.innerHTML = '';
if (isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshObj.innerHTML = Math.round(
((CMC + Water + Glycerol) / (CMC + Water + Glycerol + Flow)) * 100
);
}
</script>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh"></td>
</tr>
<tr>
<td></td>
<td>
<button id="btnReset">Reset</button
><button id="btnCalc">Calculate</button>
</td>
</tr>
</table>
</body>
</html>
Fixed code below and it works, thanks for help
<!DOCTYPE html>
<html>
<head>
</head>
<BODY>
<script type="text/javascript">
window.onload=function() {
CMCObj = document.getElementById('txtCMC');
WaterObj = document.getElementById('txtWater');
GlycerolObj = document.getElementById('txtGlycerol');
FlowObj = document.getElementById('txtFlow');
FreshObj = document.getElementById('tdFresh');
FreshCMCObj = document.getElementById('tdFreshCMC');
FreshGlycerolObj = document.getElementById('tdFreshGlycerol');
document.getElementById('btnReset').onclick = resetInputs;
document.getElementById('btnCalc').onclick = calcAddition;
}
function resetInputs() {
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
FreshCMCObj.innerHTML = '';
FreshGlycerolObj.innerHTML = '';
}
function calcAddition() {
var CMC = new Number(CMCObj.value);
var Water = new Number(WaterObj.value);
var Glycerol = new Number(GlycerolObj.value);
var Flow = new Number(FlowObj.value);
FreshObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshCMCObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshGlycerolObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert('Invalid CMC or Water');
return;
}
FreshObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
FreshCMCObj.innerHTML = Math.round(((CMC)/(CMC+Water+Glycerol+Flow)*100));
FreshGlycerolObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
}
</script>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh"></td>
</tr>
<tr>
<td>Total Fresh CMC Injection (%)</td>
<td id="tdFreshCMC"></td>
</tr>
<tr>
<td>Total Fresh Glycerol Injection (%)</td>
<td id="tdFreshGlycerol"></td>
</tr>
<tr>
<td></td>
<td><button id="btnReset">Reset</button><button id="btnCalc">Calculate</button></td>
</tr>
</table>
</body>
</html>
Alright, I made a few changes to your code making your calculator fully dynamic. If you change the FormMaker function's TotalForms variable to any number... thats how many calculators it will make for you. enjoy
:)
Also, I almost forgot to mention. Your JS script needs to be placed at the end of your HTML document and never on top. There are ways to place your JS at the top, but it should be done with built workarounds to avoid errors in your code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>My Calculator</title>
</head>
<body>
<div id="FormArea"></div>
<script type="text/javascript">
//setTimeout(FormMaker, 0);
(function StartingApp(){
setTimeout(FormMaker, 6);
})();
function FormMaker() {
let TotalForms = 3,
i,
fragment,
div,
htmlText,
Location = document.querySelector('#FormArea');
console.log(Location);
for (i = 0; i < TotalForms; i++) {
console.log('hello');
fragment = document.createDocumentFragment();
div = document.createElement('div');
htmlText = `
<h2>Amazing Calculator ${i+1}</h2>
<table>
<tr>
<td><label for="txtCMC">Total CMC Injection (ml)</label></td>
<td><input type="text" id="txtCMC${i}" /></td>
</tr>
<tr>
<td><label for="txtWater">Total Water Injection (ml)</label></td>
<td><input type="text" id="txtWater${i}" /></td>
</tr>
<tr>
<td><label for="txtGlycerol">Total Glycerol Injection (%)</label></td>
<td><input type="text" id="txtGlycerol${i}" /></td>
</tr>
<tr>
<td><label for="txtFlow">Plasticiser Flow (Lhr)</label></td>
<td><input type="text" id="txtFlow${i}" /></td>
</tr>
<tr>
<td>Total Fresh Injection (%)</td>
<td id="tdFresh${i}"></td>
</tr>
<tr>
<td></td>
<td>
<button id="btnReset${i}" onclick = "resetInputs()">Reset</button>
<button id="btnCalc${i}" onclick = "calcAddition()">Calculate</button>
</td>
</tr>
</table>
`;
div.className = 'FormContainers';
div.innerHTML = htmlText;
fragment.appendChild(div);
Location.appendChild(fragment);
};
};
function resetInputs() {
let i,
TotalForms = document.getElementsByClassName("FormContainers").length;
for (i = 0; i < TotalForms; i++) {
let CMCObj = document.getElementById(`txtCMC${i}`),
WaterObj = document.getElementById(`txtWater${i}`),
GlycerolObj = document.getElementById(`txtGlycerol${i}`),
FlowObj = document.getElementById(`txtFlow${i}`),
FreshObj = document.getElementById(`tdFresh${i}`);
CMCObj.value = '';
WaterObj.value = '';
GlycerolObj.value = '';
FlowObj.value = '';
FreshObj.innerHTML = '';
};
};
function calcAddition() {
let i,
TotalForms = document.getElementsByClassName("FormContainers").length;
for (i = 0; i < TotalForms; i++) {
let CMC = document.getElementById(`txtCMC${i}`).value,
Water = document.getElementById(`txtWater${i}`).value,
Glycerol = document.getElementById(`txtGlycerol${i}`).value,
Flow = document.getElementById(`txtFlow${i}`).value,
FreshObj = document.getElementById(`tdFresh${i}`);
FreshObj.innerHTML = '';
if(isNaN(CMC) || isNaN(Water)) {
alert(`Invalid CMC or Water on Amazing Calculator ${i}`);
return;
}
FreshObj.innerHTML = Math.round(((CMC+Water+Glycerol)/(CMC+Water+Glycerol+Flow)*100));
};
};
</script>
<style>
#FormArea{
display: flex;
flex-wrap: wrap;
}
</style>
</body>
</html>

Why does the total from last row is not calculating the sum?

I am doing a project that involves making an estimate and adding up does results. I am using the method GET and using some of the the info from the url. Also i am using WordPress to build the Web Page. Problem is that sum of the TOTAL column is not working and showing in the TOTAL row that i made. Is not an error but i think I need to add one more piece of code or change something in the javascript. So why does the id:"total" not showing the sum of the whole column? is the total.value wrong? does the id:"system_total" have a problem?
Here is how the HTML looks like:
<form >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
And here is the javascript that might have the problem:
<script>
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal()
updateModulesTotal()
updateInverterTotal()
updateAluminumTotal()
updateServiceTotal()
updateInstallationTotal()
updateDownPaymentTotal()
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
})
// FIRST ROW
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
}
document.getElementById('system_rate').addEventListener('change', updateSystemTotal)
document.getElementById('system_qty').addEventListener('change', updateSystemTotal)
// Second ROW
function updateModulesTotal() {
var output = document.getElementById('modules_total');
var quantity = Number(document.getElementById('modules_qty').value);
var modules_rate = Number(document.getElementById('modules_rate').value);
output.innerText = quantity * modules_rate;
}
document.getElementById('modules_rate').addEventListener('change', updateModulesTotal)
document.getElementById('modules_qty').addEventListener('change', updateModulesTotal)
// Third ROW
function updateInverterTotal() {
var output = document.getElementById('inverter_total');
var quantity = Number(document.getElementById('inverter_qty').value);
var inverter_rate = Number(document.getElementById('inverter_rate').value);
output.innerText = quantity * inverter_rate;
}
document.getElementById('inverter_rate').addEventListener('change', updateInverterTotal)
document.getElementById('inverter_qty').addEventListener('change', updateInverterTotal)
// Fourth ROW
function updateAluminumTotal() {
var output = document.getElementById('aluminum_total');
var quantity = Number(document.getElementById('aluminum_qty').value);
var aluminum_rate = Number(document.getElementById('aluminum_rate').value);
output.innerText = quantity * aluminum_rate;
}
document.getElementById('aluminum_rate').addEventListener('change', updateAluminumTotal)
document.getElementById('aluminum_qty').addEventListener('change', updateAluminumTotal)
// Fith ROW
function updateServiceTotal() {
var output = document.getElementById('servicedt_total');
var quantity = Number(document.getElementById('servicedt_qty').value);
var servicedt_rate = Number(document.getElementById('servicedt_rate').value);
output.innerText = quantity * servicedt_rate;
}
document.getElementById('servicedt_rate').addEventListener('change', updateServiceTotal)
document.getElementById('servicedt_qty').addEventListener('change', updateServiceTotal)
// Six ROW
function updateInstallationTotal() {
var output = document.getElementById('installation_total');
var quantity = Number(document.getElementById('installation_qty').value);
var installation_rate = Number(document.getElementById('installation_rate').value);
output.innerText = quantity * installation_rate;
}
document.getElementById('installation_rate').addEventListener('change', updateInstallationTotal)
document.getElementById('installation_qty').addEventListener('change', updateInstallationTotal)
//Seventh ROW
function updateDownPaymentTotal() {
var output = document.getElementById('dnpayment_total');
var quantity = Number(document.getElementById('dnpayment_qty').value);
var dnpayment_rate = Number(document.getElementById('dnpayment_rate').value);
output.innerText = quantity * dtpayment_rate;
}
document.getElementById('dnpayment_rate').addEventListener('change', updateDownPaymentTotal)
document.getElementById('dnpayment_qty').addEventListener('change', updateDownPaymentTotal)
// DON't TOUCH ANYTHING BELOW THIS POINT!!!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
</script>
var systemTotal = Number(document.getElementById('system').innerText);
There is no element called "system" in the snippets you provided. Are you sure you don't need to get the value from "system_total"?
Edit:
Total is showing 0 at the beginning, because the subtotals aren't initialized. To fix this, you can use your update functions before calculating the total.
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal();
updateModulesTotal();
updateInverterTotal();
updateAluminumTotal();
updateServiceTotal();
updateInstallationTotal();
updateDownPaymentTotal();
updateTotal();
})
function updateTotal() {
var total = document.getElementById('total');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
}
Further, you are updating the subtotals as soon as the user edits Quantities or Rates, but you are not updating the "Total" value.
You could call updateTotal() in your own update functions to solve this issue:
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
updateTotal();
}
Copy my code and Run it :
javascript(1.js) :
function rr() {
var system_size = document.getElementById('system_qty').value;
var system_rate_input = document.getElementById('system_rate').value;
var modules_qty = document.getElementById('modules_qty').value;
var modules_rate = document.getElementById('modules_rate').value;
var inverter_qty = document.getElementById('inverter_qty').value;
var inverter_rate = document.getElementById('inverter_rate').value;
var aluminum_qty = document.getElementById('aluminum_qty').value;
var aluminum_rate = document.getElementById('aluminum_rate').value;
var servicedt_qty = document.getElementById('servicedt_qty').value;
var servicedt_rate = document.getElementById('servicedt_rate').value;
var installation_qty = document.getElementById('installation_qty').value;
var installation_rate = document.getElementById('installation_rate').value;
var dnpayment_qty = document.getElementById('dnpayment_qty').value;
var dnpayment_rate = document.getElementById('dnpayment_rate').value;
var systemTotal = system_size * system_rate_input;
document.getElementById('system_total').innerHTML = systemTotal;
var moduleTotal = modules_rate * modules_qty;
document.getElementById('modules_total').innerHTML = moduleTotal;
var inverterTotal = inverter_qty * inverter_rate;
document.getElementById('inverter_total').innerHTML = inverterTotal;
var aluminumTotal =aluminum_qty * aluminum_rate;
document.getElementById('aluminum_total').innerHTML = aluminumTotal;
var servicedtTotal = servicedt_qty * servicedt_rate;
document.getElementById('servicedt_total').innerHTML = servicedtTotal;
var installationTotal = installation_qty * installation_rate;
document.getElementById('installation_total').innerHTML = installationTotal;
var dnpaymentTotal = dnpayment_qty * dnpayment_rate;
document.getElementById('dnpayment_total').innerHTML = dnpaymentTotal;
var Total = document.getElementById('total');
aluminum_qty = system_size * 4;
system_rate_input = 2.9 * 1000 * 1.2 * system_size;
Total.value = systemTotal + moduleTotal + inverterTotal+ aluminumTotal + servicedtTotal+ installationTotal + dnpaymentTotal;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="1.js"></script>
<form name="frm" >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input value="" id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
<button id="btn" onclick="rr()">Click</button>
</body>
</html>

Why won't my javascript function pick up my input texts when looping through table?

My function will succesfully load the dropdown values but fails to load any of the input text values. I just get an output showing blank input boxes so it's not picking up what type of input it is.
$(document).ready(function () {
$('#clicker').on('click', function (e) {
var tableToObj = function (table) {
var trs = table.rows, //replacing , with ; at end of each line
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];
for (; i < trl; i++) {
if (i === 0) {
// var sel = $(trs[i].children[j]).find('select');
//changed from input
for (; j < trs[i].children.length; j++) { //removed ; from (;
var sel = $(trs[i].children[j]).find('select'); //same as below
if (sel.length === 0) {
keys.push(trs[i].children[j].innerHTML);
} else {
keys.push(sel.find('option:selected').val());
}
var input = trs[i].children[j].value;
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) { //this works j = 0;
var sel = $(trs[i].children[j]).find('select'); //replaced " with ' around select
if (sel.length === 0) {
obj[keys[j]] = trs[i].children[j].innerHTML;
} else {
obj[keys[j]] = sel.find('option:selected').val();
}
var input = trs[i].children[j].value;
}
ret.push(obj);
}
}
return ret;
};
document.getElementById('r').innerHTML = JSON.stringify(tableToObj(document.getElementById('myTable')));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>FirstColumn</th>
<th>SecondColumn</th>
<th>ThirdColumn</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
<td>1</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option><option value="tr4">tr4</option></select></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
<tr>
<td>
<input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td>
<select><option value="tr1">tr1</option><option value="tr2">tr2</option><option value="tr3">tr3</option></select></td>
</tr>
</tbody>
</table>​​<input type="button" id="clicker" value="Click Me"/>
<br/> Result:
<fieldset id="r">
</fieldset>
<div class="ms-rtestate-read ms-rte-wpbox" contenteditable="false" unselectable="on">
<div class="ms-rtestate-notify ms-rtestate-read 9622406d-82bb-4b09-8e13-8fb81e9da538" id="div_9622406d-82bb-4b09-8e13-8fb81e9da538" unselectable="on">
</div>
<div id="vid_9622406d-82bb-4b09-8e13-8fb81e9da538" unselectable="on" style="display: none;">
</div>
</div>​<br/>
My current OBJ output is:
[{"FirstColumn":"tr1","SecondColumn":"1","ThirdColumn":"tr1"},{"FirstColumn":"1","SecondColumn":"2","ThirdColumn":"tr1"},{"FirstColumn":"","SecondColumn":"","ThirdColumn":"tr1"},{"FirstColumn":"\n ","SecondColumn":"","ThirdColumn":""},{"FirstColumn":"","SecondColumn":"","ThirdColumn":"tr1"}]

Using For-Loop to make hidden table rows appear when populated

I'm trying to pass data from one table to be used in another on the same page in javascript. The second table has rows 2-n hidden and I'd like them to dynamically appear when they're populated with data from the first table.
The first table that can be filled out looks like this:
<h3><em>Per Serving</em></h3>
<form name="ingredient-table">
<datalist id="ingredients">
<option value="Creatine Monohydrate">
<option value="St. John's Wort">
<option value="5-HTP">
<option value="Magnesium">
<option value="Magnesium Citrate">
<option value="Vitamin A">
<option value="Vitamin D3">
<option value="Cocoa">
<option value="Stevia">
<option value="Lavender Root Extract">
</datalist>
<table border="1" style="padding: 5px;">
<tr>
<td>Ingredient Name</td>
<td>Amount (in Mg)</td>
<td>% Carrier</td>
<td>$$/Kilo</td>
<td></td>
<td>Total Carrier Volume</td>
<td>Total Ingredient Volume</td>
</tr>
<tr>
<td><input type="text" id="a" list="ingredients"></input></td>
<td><input type="number" id="b"> Mg</input></td>
<td><input type="number" id="c"></input> %</td>
<td><input id="d"></input></td>
<td><button type="button" onclick="calculate('a', 'b', 'c', 'd', 'e', 'f')">Calculate Final
Volume</button></td>
<td id="e"><input></input></td>
<td id="f"><input></input></td>
<td>New Ingredient</td>
</tr>
<tr id="row2" style="display: none;">
<td><input type="text" id="h" list="ingredients"></input></td>
<td><input type="number" id="i"> Mg</input></td>
<td><input type="number" id="j"></input> %</td>
<td><input id="k"></input></td>
<td><button type="button" onclick="calculate('h', 'i', 'j', 'k', 'l', 'm')">Calculate Final
Volume</button></td>
<td id="l"><input></input></td>
<td id="m"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row3" style="display: none;">
<td><input type="text" id="o" list="ingredients"></input></td>
<td><input type="number" id="p"> Mg</input></td>
<td><input type="number" id="q"></input> %</td>
<td><input id="r"></input></td>
<td><button type="button" onclick="calculate('o', 'p', 'q', 'r', 's', 't')">Calculate Final
Volume</button></td>
<td id="s"><input></input></td>
<td id="t"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row4" style="display: none;">
<td><input type="text" id="v" list="ingredients"></input></td>
<td><input type="number" id="w"> Mg</input></td>
<td><input type="number" id="x"></input> %</td>
<td><input id="y"></input></td>
<td><button type="button" onclick="calculate('v', 'w', 'x', 'y', 'z', 'a1')">Calculate Final
Volume</button></td>
<td id="z"><input></input></td>
<td id="a1"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
<tr id="row5" style="display: none;">
<td><input type="text" id="a3" list="ingredients"></input></td>
<td><input type="number" id="a4"> Mg</input></td>
<td><input type="number" id="a5"></input> %</td>
<td><input id="a6"></input></td>
<td><button type="button" onclick="calculate('a3', 'a4', 'a5', 'a6', 'a7', 'a8')">Calculate
Final Volume</button></td>
<td id="a7"><input></input></td>
<td id="a8"><input></input></td>
<td>New Ingredient</td>
<td>Delete Ingredient</td>
</tr>
</table>
</form>
The second table that accepts the data from the above table is this:
<h3>Per Bottle</h3>
<button type="button" onclick="bottle_volume('td1', 'td2', 'td3', 'td4', 'td5', 'td6', 'td7',
'td8','td9', 'td10', 'td11', 'td12', 'td13', 'td14', 'td15', 'td16', 'td17', 'td18', 'td19',
'td20')">Click to Calculate Bottle Totals</button>
<table border="1" style="padding: 5px;">
<tr>
<td>Ingredient</td>
<td>Total Amount of Carrier</td>
<td>Total Per Bottle</td>
<td>Total Cost Per Bottle</td>
</tr>
<tr id="outputRow1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
<tr id="outputRow2" style="display: none;">
<td id="td5"><input></input></td>
<td id="td6"><input></input></td>
<td id="td7"><input></input></td>
<td id="td8"><input></input></td>
</tr>
<tr id="outputRow3" style="display: none;">
<td id="td9"><input></input></td>
<td id="td10"><input></input></td>
<td id="td11"><input></input></td>
<td id="td12"><input></input></td>
</tr>
<tr id="outputRow4" style="display: none;">
<td id="td13"><input></input></td>
<td id="td14"><input></input></td>
<td id="td15"><input></input></td>
<td id="td16"><input></input></td>
</tr>
<tr id="outputRow5" style="display: none;">
<td id="td17"><input></input></td>
<td id="td18"><input></input></td>
<td id="td19"><input></input></td>
<td id="td20"><input></input></td>
</tr>
<tr>
<td id="td21"><strong>Totals</strong></td>
<td id="td22"></td>
<td id="td23"></td>
<td id="td24"></td>
</tr>
</table>
The for-loop I use on the second table to make the rows appear is this:
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
else {
document.getElementById(rowArray[i]).style.display = 'none';
}
}
This doesn't cause the hidden rows to appear when they're populated. It doesn't seem to have any effect at all, and also does not cause any errors to appear in the javascript console.
The entire function that happens when you hit the button "Click to Calculate Bottle Totals"
is bottle_volume('td1', 'td2',...) and it looks like this:
var bottle_volume = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11,
arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20) {
var ing1Value = calculate('a', 'b', 'c', 'd', 'e', 'f');
var ing1 = ing1Value[0];
var ing1_carrier = ing1Value[3]*30;
var ing1_volume = ing1Value[4]*30;
var ing1_cost = (ing1_volume/1000000)*ing1Value[2];
var name1 = document.getElementById(arg1).innerHTML = ing1;
var carrier1 = document.getElementById(arg2).innerHTML = ing1_carrier.toFixed(2)*1;
var ing_volume1 = document.getElementById(arg3).innerHTML = ing1_volume.toFixed(2)*1;
var ingCost1 = document.getElementById(arg4).innerHTML ="$" + ing1_cost.toFixed(2)*1;
var ing2Value = calculate('h', 'i', 'j', 'k', 'l', 'm');
var ing2 = ing2Value[0];
var ing2_carrier = ing2Value[3]*30;
var ing2_volume = ing2Value[4]*30;
var ing2_cost = (ing2_volume/1000000)*ing2Value[2];
var name2 = document.getElementById(arg5).innerHTML = ing2;
var carrier2 = document.getElementById(arg6).innerHTML = ing2_carrier.toFixed(2)*1;
var ing_volume2 = document.getElementById(arg7).innerHTML = ing2_volume.toFixed(2)*1;
var ingCost2 = document.getElementById(arg8).innerHTML = "$" + ing2_cost.toFixed(2)*1;
var ing3Value = calculate('o', 'p', 'q', 'r', 's', 't');
var ing3 = ing3Value[0];
var ing3_carrier = ing3Value[3]*30;
var ing3_volume = ing3Value[4]*30;
var ing3_cost = (ing3_volume/1000000)*ing3Value[2];
var name3 = document.getElementById(arg9).innerHTML = ing3;
var carrier3 = document.getElementById(arg10).innerHTML = ing3_carrier.toFixed(2)*1;
var ing_volume3 = document.getElementById(arg11).innerHTML = ing3_volume.toFixed(2)*1;
var ingCost3 = document.getElementById(arg12).innerHTML = "$" + ing3_cost.toFixed(2)*1;
var ing4Value = calculate('v', 'w', 'x', 'y', 'z', 'a1');
var ing4 = ing4Value[0];
var ing4_carrier = ing4Value[3]*30;
var ing4_volume = ing4Value[4]*30;
var ing4_cost = (ing4_volume/1000000)*ing4Value[2];
var name4 = document.getElementById(arg13).innerHTML = ing4;
var carrier4 = document.getElementById(arg14).innerHTML = ing4_carrier.toFixed(2)*1;
var ing_volume4 = document.getElementById(arg15).innerHTML = ing4_volume.toFixed(2)*1;
var ingCost4 = document.getElementById(arg16).innerHTML = "$" + ing4_cost.toFixed(2)*1;
var ing5Value = calculate('a3', 'a4', 'a5', 'a6', 'a7', 'a8');
var ing5 = ing5Value[0];
var ing5_carrier = ing5Value[3]*30;
var ing5_volume = ing5Value[4]*30;
var ing5_cost = (ing5_volume/1000000)*ing5Value[2];
var name5 = document.getElementById(arg17).innerHTML = ing5;
var carrier5 = document.getElementById(arg18).innerHTML = ing5_carrier.toFixed(2)*1;
var ing_volume5 = document.getElementById(arg19).innerHTML = ing5_volume.toFixed(2)*1;
var ingCost5 = document.getElementById(arg20).innerHTML = "$" + ing5_cost.toFixed(2)*1;
carrierPerBottle = ing1_carrier + ing2_carrier + ing3_carrier + ing4_carrier + ing5_carrier;
volumePerBottle = ing1_volume + ing2_volume + ing3_volume + ing4_volume + ing5_volume;
costPerBottle = ing1_cost + ing2_cost + ing3_cost + ing4_cost + ing5_cost;
document.getElementById("td22").innerHTML = carrierPerBottle.toFixed(2)*1;
document.getElementById("td23").innerHTML = volumePerBottle.toFixed(2)*1;
document.getElementById("td24").innerHTML = "$" + costPerBottle.toFixed(2)*1;
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
else {
document.getElementById(rowArray[i]).style.display = 'none';
}
};
};
I'm not sure what's wrong with my for-loop. I'm only using javascript for this and would prefer not to use jquery.
You can see the whole page here: Supplement Pricer
This is the rendered HTML for outputRow1:
<tr id="outputRow1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
Same goes for outputRow2, outputRow3, outputRow4 and outputRow5, but they have different elements in their <td>.
When you call this function in Javascript:
var rowArray = ["outputRow1", "outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).innerHTML !== "") {
...
You're checking to see if outputRow1 has anything in it's Inner HTML, which it does. Therefore, it's going to display the row no matter what.
Basically, you need to check if their corresponding rows are set to display:none or display:table-row and display the outputRowN accordingly. I think this will work, but give it a try:
var rowArray = ["row2", "row3", "row4", "row5"]; // Skip row 1, always shows;
var outputArray = ["outputRow2", "outputRow3", "outputRow4", "outputRow5"];
for (i = 0; i < rowArray.length; i++) {
if (document.getElementById(rowArray[i]).getAttribute("style") != "display: none;"){
console.log("True");
document.getElementById(outputArray[i]).setAttribute("style", "");
} else {
console.log("False");
document.getElementById(outputArray[i]).setAttribute("style", "display: none;");
}
}
FINAL EDIT
Working Fiddle Example:
JSFiddle
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = 'table row';
}
try changing the above code to (take out 'table row'):
if (document.getElementById(rowArray[i]).innerHTML !== "") {
document.getElementById(rowArray[i]).style.display = '';
}
i dont know if this will work, but its easier to post code in code format in the answer box then make a comment for it.
so i came up with another answer that requires at least one of the inputs of a row from table 1 to be filled out in order for the corresponding row in table 2 to be shown. i require one input to have at least some contents because if its based on if the row from table 1 is showing, you would just have a bunch of 0's in a bunch of rows in table 2.
heres the demo: http://jsfiddle.net/swm53ran/50/
calculate<br/><br/>
table 1<br/>
<table border="1" style="padding: 5px;">
<tr id="row1">
<td id="td1"><input></input></td>
<td id="td2"><input></input></td>
</tr>
<tr id="row2">
<td id="td3"><input></input></td>
<td id="td4"><input></input></td>
</tr>
<tr id="row3">
<td id="td5"><input></input></td>
<td id="td6"><input></input></td>
</tr>
</table>
<br/>
table 2<br/>
<table border="1" style="padding: 5px;" class="table2">
<tr id="outputRow1">
<td><input value="row1"></input></td>
<td><input></input></td>
</tr>
<tr id="outputRow2" style="display:none;">
<td><input value="row2"></input></td>
<td><input></input></td>
</tr>
<tr id="outputRow3" style="display:none;">
<td><input value="row3"></input></td>
<td><input></input></td>
</tr>
</table>
<script>
function populate() {
var rowArray = ["row2", "row3"];
var outArray = ["outputRow2", "outputRow3"];
for (i = 0; i < rowArray.length; i++) {
var inputs = document.getElementById(rowArray[i]).getElementsByTagName('input'); // get the inputs of table 1 row
var show = false;
for (j = 0; j < inputs.length; j++) {
if (inputs[j].value.length > 0) { // if at least one text box has contents, show = true
show = true;
}
}
if (show == true) {
document.getElementById(outArray[i]).style.display = "table-row";
}
else {
document.getElementById(outArray[i]).style.display = "none";
}
}
}
</script>
when the information from the text boxes of a given row are all empty in table 1, the row in table 2 will hide. hope this is suitable for your needs.

Pass a field calculation in html to another field in the SAME form

So, I can only find how to pass the information to another page not the same page and this has to be done entirely on the client side, no server side work as there will be no internet connection when this is used, hence the mailto for the form data so it can be sent when a connection is available.
Basically I have two tables, one on the left that has a standard set of numbers (fields time1-time8) that the user can change if need be. These values total into the 'designhours' field. That number must be put into the 'designhours' field on the right side for the various calculations needed there. In my former work (not HTML or javascript) if the field name was the same the data was passed, obviously not the case here.
Before I put the table on the left in, this form worked beautifully, but now I need to add the option of totaling a new 'designhours' value. Many thanks to those that have helped me before and many thanks to anyone that helps now. I am still learning, but I am getting there.
Sample code with most fields removed so you can see what I am doing (thanks for pointing out) Full code way below...
So the field names in the left table
time1 - time8
those values are added to put the total in designhours
And the right table
wage, instructors, class, designhours (which is the same as in the left table), cost, many, atetextfield7, build_cost, buy_cost, build_hours, buy_hours, build_train, buy_train, build_total, buy_total
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
var wageval = parseInt(document.getElementById('wage').value) || 0;
var instructorsval = parseInt(document.getElementById('instructors').value) || 0;
var build_cost = document.getElementById('build_cost');
var buy_cost = document.getElementById('buy_cost');
var msg = [];
if (isNaN(wageval)) {
msg.push('Average instructor hourly wage is not a number');
// the value isn't a number
}
if (isNaN(instructorsval)) {
msg.push('Number of instructors per course is not a number');
// the value isn't a number
}
if (msg.length > 0)   {
build_cost.value = msg.join(', ');
buy_cost.value = msg.join(', ');
and the calculations below:
} else {
designhours.value = (time1 + time2 + time3 + time4 + time5 + time6 + time7 + time8);
build_cost.value = (wageval * designhoursval);
buy_cost.value = (costval * hiddenval);
build_hours.value = (designhoursval * manyval);
build_train.value = (classval * hiddenval);
build_total.value = (wageval * designhoursval * manyval + classval);
buy_total.value = (costval * manyval);
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
}
Full Code below
HTML
<form id="form1" name="form1" method="post" action="mailto:?subject=Laerdal%20ROI%20Information" enctype="text/plain">
<table width="859" border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="bottom">
<table width="352" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="22" colspan="2"> </td>
</tr>
<tr>
<td width="225" height="22"> </td>
<td width="127" height="22" align="left"> </td>
</tr>
<tr>
<td height="22"><span class="norm">Needs Analysis</span></td>
<td height="22" align="center"><input name="time1" type="text" class="field" id="time1" value="1" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Research</span></td>
<td height="22" align="center"><input name="time2" type="text" class="field" id="time2" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Design</span></td>
<td height="22" align="center"><input name="time3" type="text" class="field" id="time3" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Scenario Programming</span></td>
<td height="22" align="center"><input name="time4" type="text" class="field" id="time4" value="3" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Support Materials</span></td>
<td height="22" align="center"><input name="time5" type="text" class="field" id="time5" value="16" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Validation</span></td>
<td height="22" align="center"><input name="time6" type="text" class="field" id="time6" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Revision</span></td>
<td height="22" align="center"><input name="time7" type="text" class="field" id="time7" value="4" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Implementation</span></td>
<td height="22" align="center"><input name="time8" type="text" class="field" id="time8" value="2" size="10" /></td>
</tr>
<tr>
<td height="22"><span class="norm">Total</span></td>
<td height="22" align="center"><input name="designhours" class="field" type="text" id="designhours" size="10" /></td>
</tr>
<tr>
<td height="73" colspan="2"> </td>
</tr>
</table>
<p> </p></td>
<td width="55" valign="bottom"> </td>
<td>
<table width="440" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="36" colspan="2" align="right" class="norm">Average Instructor hourly wage:</td>
<td height="36" align="right"><input name="wage" class="field" type="text" id="wage" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Number of Instructors per course:</td>
<td height="36" align="right"><input name="instructors" class="field" type="text" id="instructors" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Scenario Programing Class:</td>
<td height="36" align="right"><input name="class" class="field" type="text" id="class" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Instruction design hours per scenarios:</td>
<td height="36" align="right"><input name="designhours" class="field" type="text" readonly="true" id="designhours" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Average cost of SimStore Scenarios:</td>
<td height="36" align="right"><input name="cost" class="field" type="text" id="cost" value="295" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">How many scenarios do you need:</td>
<td height="36" align="right"><input name="many" class="field" type="text" id="many" size="12" /></td>
</tr>
<tr>
<td height="36" colspan="2" align="right" class="norm">Date needed?:</td>
<td height="36" align="right"><input name="atetextfield7" class="field" type="text" id="atetextfield7" size="12" /></td>
</tr>
<tr>
<td height="40" colspan="3" align="center" class="calc">CALCULATED RESULTS</td>
</tr>
<tr>
<td height="40"><input name="hidden" type="hidden" id="hidden" value="1" /></td>
<td height="40" align="center" class="bold">BUILD</td>
<td height="40" align="center" class="bold">BUY</td>
</tr>
<tr>
<td height="38" align="right" class="norm">Cost per scenario:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_cost" class="field" type="text" id="build_cost" size="12" /></td>
<td height="38" align="center"><input name="buy_cost" class="field" type="text" id="buy_cost" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">Total development hours:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_hours" class="field" type="text" id="build_hours" size="12" /></td>
<td height="38" align="center"><input name="buy_hours" class="field" type="text" id="buy_hours" value="0" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">
Scenario Programming<img src="images/Blank.png" alt="" width="12" height="5" /><br />
Training (8h):<img src="Blank.png" alt="" width="12" height="5" />
</td>
<td height="38" align="center"><input name="build_train" class="field" type="text" id="build_train" size="12" /></td>
<td height="38" align="center"><input name="buy_train" class="field" type="text" id="buy_train" value="0" size="12" /></td>
</tr>
<tr>
<td height="38" align="right" class="norm">Total Cost:<img src="images/Blank.png" alt="" width="12" height="5" /></td>
<td height="38" align="center"><input name="build_total" class="field" type="text" id="build_total" size="12" /></td>
<td height="38" align="center"><input name="buy_total" class="field" type="text" id="buy_total" size="12" /></td>
</tr>
<tr>
<td height="50" colspan="3" align="center" valign="bottom"><input type="reset" />
<img src="images/Blank.png" alt="" width="15" height="25" />
<input name="calculate" type="button" id="calculate" value="Calculate" />
<img src="images/Blank.png" alt="" width="15" height="25" />
<input name="share" type="submit" id="submit" value="Share" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
Javascript
var btn = document.getElementById('calculate');
btn.onclick = function () {
//get the input values
var wageval = parseInt(document.getElementById('wage').value) || 0;
var instructorsval = parseInt(document.getElementById('instructors').value) || 0;
var classval = parseInt(document.getElementById('class').value) || 0;
var designhoursval = parseInt(document.getElementById('designhours').value) || 0;
var costval = parseInt(document.getElementById('cost').value) || 0;
var manyval = parseInt(document.getElementById('many').value) || 0;
var hiddenval = parseInt(document.getElementById('hidden').value) || 0;
var time1val = parseInt(document.getElementById('time1').value) || 0;
var time2val = parseInt(document.getElementById('time2').value) || 0;
var time3val = parseInt(document.getElementById('time3').value) || 0;
var time4val = parseInt(document.getElementById('time4').value) || 0;
var time5val = parseInt(document.getElementById('time5').value) || 0;
var time6val = parseInt(document.getElementById('time6').value) || 0;
var time7val = parseInt(document.getElementById('time7').value) || 0;
var time8val = parseInt(document.getElementById('time8').value) || 0;
// get the elements to hold the results
var build_cost = document.getElementById('build_cost');
var buy_cost = document.getElementById('buy_cost');
var build_hours = document.getElementById('build_hours');
var buy_hours = document.getElementById('buy_hours');
var build_total = document.getElementById('build_total');
var build_train = document.getElementById('build_train');
var buy_total = document.getElementById('buy_total');
var time1 = document.getElementById('time1');
var time2 = document.getElementById('time1');
var time3 = document.getElementById('time1');
var time4 = document.getElementById('time1');
var time5 = document.getElementById('time1');
var time6 = document.getElementById('time1');
var time7 = document.getElementById('time1');
var time8 = document.getElementById('time1');
var designhours = document.getElementById('designhours');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(wageval)) {
msg.push('Average instructor hourly wage is not a number');
// the value isn't a number
}
if (isNaN(instructorsval)) {
msg.push('Number of instructors per course is not a number');
// the value isn't a number
}
if (isNaN(classval)) {
msg.push('Scenario programming class is not a number');
// the value isn't a number
}
if (isNaN(designhoursval)) {
msg.push('Instruction design hours per scenario is not a number');
// the value isn't a number
}
if (isNaN(costval)) {
msg.push('Average cost of SimStore scenarios is not a number');
// the value isn't a number
}
if (isNaN(manyval)) {
msg.push('How many scenarios do you need is not a number');
// the value isn't a number
}
if (isNaN(hiddenval)) {
msg.push('joe messed up');
// the value isn't a number
}
if (isNaN(time1val)) {
msg.push('Needs Analysis is not a number');
// the value isn't a number
}
if (isNaN(time2val)) {
msg.push('Research is not a number');
// the value isn't a number
}
if (isNaN(time3val)) {
msg.push('Design is not a number');
// the value isn't a number
}
if (isNaN(time4val)) {
msg.push('Scenario Programming is not a number');
// the value isn't a number
}
if (isNaN(time5val)) {
msg.push('Support Materials is not a number');
// the value isn't a number
}
if (isNaN(time6val)) {
msg.push('Validation is not a number');
// the value isn't a number
}
if (isNaN(time7val)) {
msg.push('Revision is not a number');
// the value isn't a number
}
if (isNaN(time8val)) {
msg.push('Implementation is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0)  {
build_cost.value = msg.join(', ');
buy_cost.value = msg.join(', ');
build_hours.value = msg.join(', ');
build_train.value = msg.join(', ');
build_total.value = msg.join(', ');
buy_total.value = msg.join(', ');
time1.value = msg.join(', ');
time2.value = msg.join(', ');
time3.value = msg.join(', ');
time4.value = msg.join(', ');
time5.value = msg.join(', ');
time6.value = msg.join(', ');
time7.value = msg.join(', ');
time8.value = msg.join(', ');
} else {
designhours.value = (time1 + time2 + time3 + time4 + time5 + time6 + time7 + time8);
build_cost.value = (wageval * designhoursval);
buy_cost.value = (costval * hiddenval);
build_hours.value = (designhoursval * manyval);
build_train.value = (classval * hiddenval);
build_total.value = (wageval * designhoursval * manyval + classval);
buy_total.value = (costval * manyval);
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
}
};
Thanks again for any guidance anyone can give. I'm struggling through all of this.
First of all, no idea what these are for:
var time1 = document.getElementById('time1');
var time2 = document.getElementById('time1');
var time3 = document.getElementById('time1');
var time4 = document.getElementById('time1');
var time5 = document.getElementById('time1');
var time6 = document.getElementById('time1');
var time7 = document.getElementById('time1');
var time8 = document.getElementById('time1');
Then, you only have the element as var in timex.
So the simplest fix is:
designhours.value = time1val + time2val + time3val + time4val + time5val + time6val + time7val + time8val;
instead of:
designhours.value = time1 + time2 + time3 + time4 + time5 + time8 + time7 + time8;
See where you went wrong? You were adding objects (the input fields) together, not their values (that you already had to begin with).
And note, digits in a input field are not numbers but a string.
You also might want to specify a radix with parseInt like parseInt(val,10);
Finally you could re-factor the code quite a bit, this is indeed a bit much (but good on ya for providing useful error-detection).
See this fiddle: http://jsfiddle.net/4nHvc/1/
UPDATE: upon further inspection there is a lot more wrong:
Why are these function local variables set at the end of your function?
var build_costval = parseInt(build_cost.value) || 0;
var buy_costval = parseInt(buy_cost.value) || 0;
var build_hoursval = parseInt(build_hours.value) || 0;
var build_trainval = parseInt(build_train.value) || 0;
var build_totalval = parseInt(build_total.value) || 0;
var buy_totalval = parseInt(buy_total.value) || 0;
var designhoursval = parseInt(designhours.value) || 0;
The very next line of javascript after the first one where you used the wrong variable names (thus adding objects instead of their values) can't work then either:
build_cost.value = (wageval * designhoursval);
Well, if you get the value of the inputfield designhoursval at the start of the code, that field is still empty.. So then when the script executes the above line, what is designhoursval ??? right, empty. If for instance you re-read that value using the last block of 'useless' code WITHOUT the var variable declaration (you declared it already at the start of your function) and place it above that line, then another field of your calculator starts to work:
designhoursval = parseInt(designhours.value) || 0;
build_cost.value = (wageval * designhoursval);
But then.. isn't it easier to first get al the input-values, do the math, then output the values?
See this fiddle, now it almost works: http://jsfiddle.net/4nHvc/2/
update your time values...
var time1 = parseInt(document.getElementById('time1').value);
var time2 = parseInt(document.getElementById('time1').value);
var time3 = parseInt(document.getElementById('time1').value);
var time4 = parseInt(document.getElementById('time1').value);
var time5 = parseInt(document.getElementById('time1').value);
var time6 = parseInt(document.getElementById('time1').value);
var time7 = parseInt(document.getElementById('time1').value);
var time8 = parseInt(document.getElementById('time1').value);
Also, I'm not sure how you wired up your button to your script, so I changed your function...
function doThis() {
and your button...
<input name="calculate" type="button" id="calculate" value="Calculate" onclick="doThis()" />
Those may have been fine in your code, but that part was omitted in your post so check it out. (You can just use an "alert('foo');" to check.)

Categories

Resources