I'm creating a lengthy form. There's 5 different sections for you to mark off if you qualify (checkmarks). Probably 50 questions total. Each section has a different weight/points (section 1 is 1 point each, section 2 is 3 points each etc). How can I display the total score and does my script calculation look ok? Sorry I'm fairly new at this. Didn't include the entire form because it's very long.
<script language="JavaScript1.1" type="text/javascript">
/* <![CDATA[ */
var calctxt = '';
var xmltxt = '';
var htmtxt = '';
function DVTScoreWells_fx() {
with(document.DVTScoreWells_form){
Score = 0.0;
doCalc = true;
if (1PQ1.checked){
Score = Score + 1;
}
if (1PQ2.checked){
Score = Score + 1;
}
if (1PQ3.checked){
Score = Score + 1;
}
if (1PQ4.checked){
Score = Score + 1;
}
if (1PQ5.checked){
Score = Score + 1;
}
if (1PQ6.checked){
Score = Score + 1;
}
if (1PQ7.checked){
Score = Score + 1;
}
if (1PQ8.checked){
Score = Score + 1;
}
if (1PQ9.checked){
Score = Score + 1;
}
if (1PQ10.checked){
Score = Score + 1;
}
if (1PQ11.checked){
Score = Score + 1;
}
if (1PQ12.checked){
Score = Score + 1;
}
if (1PQ13.checked){
Score = Score + 1;
}
if (1PQ14.checked){
Score = Score + 1;
}
if (1PQ15.checked){
Score = Score + 1;
}
if (2PQ1.checked){
Score = Score + 2;
}
if (2PQ2.checked){
Score = Score + 2;
}
if (2PQ3.checked){
Score = Score + 2;
}
cctotal.value = Score;
if (doCalc){
rrclr();
}
}
}
</script>
<form name="DVTScoreWells_form" id="DVTScoreWells_form" action="#" onsubmit="return false;" onreset="rrclr();">
<br><br>
<p>Are you at risk for DVT? Fill out this Risk Assessment and take a look.</p><br><br>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#FFFFFF" cellpadding="200" cellspacing="200" class="bodyContainer">
<tbody>
<tr>
<td class="leftSidebar" sectionid="leftSidebar" valign="top">
<div>
<div>
<div class="title" style="text-align:left">
<div class="title" contentid="title" style="text-align: left;">
<div>
<div>
<span style="text-decoration: none;"><span style="font-family: Comic Sans MS; font-size: 18pt;">Each Risk Factor
Represents 1 Point</span></span>
</div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<div>
<table class="infusion-field-container" style="width:270;">
<tbody>
<tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ1" name="1PQ1" type="checkbox" onclick="DVTScoreWells_fx();"
/>
<label for="1PQ1">Age 41 - 59</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ2" name="1PQ2" type="checkbox" onclick="DVTScoreWells_fx();"
/>
<label for="1PQ2">Minor surgery planned</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ3" name="1PQ3" type="checkbox" onclick="DVTScoreWells_fx
();"/>
<label for="1PQ3">History of prior major surgery</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ4" name="1PQ4" type="checkbox" onclick="DVTScoreWells_fx
();"/>
<label for="1PQ4">Varicose veins</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ5" name="1PQ5" type="checkbox" onclick="DVTScoreWells_fx
();"/>
<label for="1PQ5">History of inflammatory bowel disease</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ6" name="1PQ6" type="checkbox" onclick="DVTScoreWells_fx
();"/>
<label for="1PQ6">Swollen legs (current)</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ7" name="1PQ7" type="checkbox" onclick="DVTScoreWells_fx
();"/>
<label for="1PQ7">Obesity (BMI >30)</label>
</td>
</tr><tr>
</td>
</tr><tr>
<td class="infusion-field-input-container" style="width:270px;">
<input class="infusion-field-input-container" id="1PQ8" name="1PQ8" type="checkbox" onclick="DVTScoreWells_fx
();"/>
Honestly the way your current code approaches this is prone to errors via typos or omission, as well as will be a pain to maintain.
My main suggestion is to leverage a div with the id of Score that contains the running total, and have each checkbox call a function with their value as an argument that adjusts the innerHTML of score, eg:
HTML:
Your Risk is <span id='risklevel'>Low</span> (<span id='score'>0</span>)
<input type='checkbox' onchange='updateScore(this,3);' />
JS:
function updateScore(ele,val){
var score = document.getElementById('score');
var riskLevel = document.getElementById('risklevel');
var curScore = parseFloat(score.innerHTML);
curScore += (ele.checked ? val : -val);
score.innerHTML = curScore;
if(curScore <= 1){
riskLevel.innerHTML = "Low";
}else if(curScore <= 2){
riskLevel.innerHTML = "Moderate";
}else if(curScore <= 4){
riskLevel.innerHTML = "High";
}else{
riskLevel.innerHTML = "Very High";
}
}
OR
If you wanna stick with a calc-all-at-once approach...
Tag the checkboxes with their section in some natively dom-searchable way (I suggest classes prefixed with data- (eg: data-riskFactorSet )), give each one a data-* attribute (such as data-riskvalue) and have your js iterate over all checkboxen, combining the int/float value of the data-* attribute.
NOTE: since it's a less popular construct...
(ele.checked ? val : -val) uses a Ternary operator. Think of it like an in-line if-then-else statement, with the stipulation that the return types of the true and false parts must be the same. It works like this:
test ? ifTrue : ifFalse
Related
I am unsure of what I have done wrong in my simple sales tax calculator. When I press submit I want a dollar amount of the item cost plus sales tax to be shown but instead I see total tip $functionround(){[native code]}.
//calculation
var total = (itemCost * salesTax + itemCost);
total = Math.round
total = Math.round
In the line above you are assigning the value of the function Math.round to the variable total. Instead you probably want to assign the value returned by the function Math.round to your total variable like this:
total = Math.round(total)
You should consider those codes on the calculation. Here is a simple tax calculator and it works well:
function fmtPrice(value) {
result="$"+Math.floor(value)+".";
var cents=100*(value-Math.floor(value))+0.5;
result += Math.floor(cents/10);
result += Math.floor(cents%10);
return result;
}
function compute() {
var unformatted_tax = (document.forms[0].cost.value)*(document.forms[0].tax.value);
document.forms[0].unformatted_tax.value=unformatted_tax;
var formatted_tax = fmtPrice(unformatted_tax);
document.forms[0].formatted_tax.value=formatted_tax;
var cost3= eval( document.forms[0].cost.value );
cost3 += eval( (document.forms[0].cost.value)*(document.forms[0].tax.value) );
var total_cost = fmtPrice(cost3);
document.forms[0].total_cost.value=total_cost;
}
function resetIt() {
document.forms[0].cost.value="19.95"; // cost of product
document.forms[0].tax.value=".06"; // tax value
document.forms[0].unformatted_tax.value="";
document.forms[0].formatted_tax.value="";
document.forms[0].total_cost.value="";
}
<CENTER>
<FORM>
<TABLE BORDER=2 WIDTH=300 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Cost</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Tax</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="cost" VALUE="19.95" SIZE=10>
<TD align="center"><INPUT TYPE="text" NAME="tax" VALUE=".06" SIZE=10>
</TR>
</TABLE>
<BR>
<TABLE BORDER=1 WIDTH=600 CELLPADDING=3>
<TR>
<TD align="center"><FONT SIZE=+1><STRONG>Unformatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>Formatted Tax</STRONG></FONT>
<TD align="center"><FONT SIZE=+1><STRONG>TOTAL COST</STRONG></FONT>
</TR>
<TR>
<TD align="center"><INPUT TYPE="text" NAME="unformatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="formatted_tax" SIZE=15>
<TD align="center"><INPUT TYPE="text" NAME="total_cost" SIZE=15>
</TR>
</TABLE>
<BR>
<TABLE BORDER=0 WIDTH=400 CELLPADDING=5>
<TR>
<TD align="center"><INPUT TYPE="reset" VALUE="RESET" onClick="resetIt()">
<TD align="center"><INPUT TYPE="button" VALUE="COMPUTE" onclick="compute()">
</TR>
</TABLE>
</CENTER>
As noted you need to return the total of hte Math.round - but you also need to parse the values into numbers) and then you also have to remember that the sales tax is a percentage - so it has to be divided by 100.
I have amended your logic to
a) parse the values of the inputs into numbers using parseInt()
b) resolve the math.round() issue
c) get the sales tax value by multiplying the item cost by the sales tax percentage ... itemCost * (salesTax/100)
d) add the sales tax value to the item cost ... item cost + (itemCost * (salesTax/100))...
//Function
function calculateTip() {
var itemCost = parseInt(document.getElementById("itemCost").value);
var salesTax = parseInt(document.getElementById("salesTax").value);
//enter values window
if (itemCost === "" || salesTax == "") {
window.alert("Please enter the values!");
return;
}
//calculation
var total = Math.round(itemCost + (itemCost * salesTax/100));
//display amount
document.getElementById("totalTip").style.display = "block";
document.getElementById("amount").innerHTML = total;
}
//Hide Tip Amount and call our function with a button
document.getElementById("totalTip").style.display = "none";
document.getElementById("submit").onclick = function() {
calculateTip();
};
</head>
<body id="color">
<div class="container" id="contain">
<div class="text-center">
<h1>Sales Tax Calculator</h1>
<p> Amount Before Tax?</p>
$ <input id="itemCost" type="text" placeholder="item cost">
<p>Sales Tax Percentage?</p>
<input id="salesTax" type="text" placeholder="sales tax percent"><br><br>
<button type="submit" id="submit">submit</button>
</div>
<div class="container" ID="totalTip">
<div class="text-center">
<p>Total Tip</p>
<sup>$</sup><span id="amount">0.00</span>
</div>
</div>
</div>
<script type="text/javascript" src="javascript.js"></script>
</body>
I am in the process of writing a webpage. I have everything done that is needed, however, when you enter any quantity over 30 it will make the id = "shipping" color red. It does this but it does it for anything less than 30 as well. Also I am having trouble with my submit button sending off to a server/url. Any help is appreciated! I will attach my code!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Widgets R' Us </title>
<style>
table,
td {
border: 1px solid black;
}
</style>
<script type="text/javascript">
//Check if non -number or a negative number
function realNumber() {
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
//isNaN is a predetermined function
if ((isNaN(qty1) || qty1 < 0) || (isNaN(qty2) || qty2 < 0) || (isNaN(qty3) || qty3 < 0)) {
alert("The quantity given is not a real number or is a negative number!");
return false; //Will not allow for data to go to server.
} else {
return true;
}
}
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
} else {
document.getElementById("shipping").style.color = "black";
}
}
}
function checkOut() {
if (total()) {
if ((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked)) {
return true;
}
}
return false;
}
</script>
</head>
<body>
<div>
<h1><b><big> Widgets R' Us </b></strong>
</h1>
<h2><b> Order/Checkout </b></h2>
<form name "widgets" onsubmit="return checkOut();" action="https://www.reddit.com/" method="get">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" /</td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" /</td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99" /></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0" /></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Product Total:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()" /> </td>
</tr>
</form>
</body>
</html>
Problem with your values qty1,qty2,qty3. these values are reading as string. so instead of addding these values , its concatinating the strings. replace
var qty1 = document.getElementById("Quantity1").value;
var qty2 = document.getElementById("Quantity2").value;
var qty3 = document.getElementById("Quantity3").value;
with
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
It will Solve your problem with 'Red'.
For the submit button, function total() is not returning anything. so change something like
function total() {
var p1 = document.getElementById("Price1").value; //Value is referenced to the input tag
var p2 = document.getElementById("Price2").value;
var p3 = document.getElementById("Price3").value;
var qty1 = parseInt(document.getElementById("Quantity1").value);
var qty2 = parseInt(document.getElementById("Quantity2").value);
var qty3 = parseInt(document.getElementById("Quantity3").value);
var over = qty1 + qty2 + qty3;
if (realNumber()) {
var totals = (p1 * qty1) + (p2 * qty2) + (p3 * qty3);
var yes = (totals).toFixed(2);
document.getElementById("ProductTotal").innerHTML = "$" + yes;
if (over > 30) {
document.getElementById("shipping").style.color = "red";
return true;
} else if(over>0) {
document.getElementById("shipping").style.color = "black";
return true;
}else{
document.getElementById("shipping").style.color = "black";
return false;
}
}
}
and checkout() as
function checkOut() {
if (total()) {
if (((document.getElementById("shipping").style.color == "red") &&
(document.getElementById("extra").checked))||
(document.getElementById("shipping").style.color != "red")) {
return true;
}
}
return false;
}
Replace
var over = qty1 + qty2 + qty3;
With
var over = parseInt(qty1) + parseInt(qty2) + parseInt(qty3);
There were some minor HTML errors but the real issue is that numeric strings were being concatenated. So, to get the quantity values you need to use parseInt() to extract the integer value so that math is performed instead of string concatenation. Also, it's a little odd that the user has to click the Calculate Button in order to see a total. The button does work correctly, but is this what you really want?
One more thing, as tempting as it may be to directly alter the color of elements with JavaScript, in terms of keeping the code more robust, it is preferable to simply change the class name as the code does in this example since I created two classes in the CSS for this purpose.
The form now submits as long as the checkbox is unchecked and the units do not exceed 30. I changed the method to "post" and adjusted the true/false return statements in checkOut(). Note when data is submitted using the POST method, then no form data appears appended to the URL; for more info see here. I also altered the totals() function so that now it returns a value, namely the total price.
var d = document;
d.g = d.getElementById;
var qty = [0, 0, 0, 0];
var shipping = d.g("shipping");
function realNumber() {
var qtyInvalid = [0, 0, 0, 0];
for (let i = 1, max = qtyInvalid.length; i < max; i++) {
qtyInvalid[i] = (isNaN(qty[i]) || qty[i] < 0);
}
if (qtyInvalid[1] || qtyInvalid[2] || qtyInvalid[3]) {
console.log("The quantity given is not a real number or is a negative number!");
return false;
}
return true;
}
function total() {
var over = 0;
var price = [0, 0, 0, 0];
for (j = 1, max = price.length; j < max; j++) {
price[j] = d.g("Price" + j + "").value;
qty[j] = d.g("Quantity" + j + "").value;
}
var totals = 0;
var yes = 0;
const radix = 10;
for (q = 1, max = qty.length; q < max; q++) {
over += parseInt(qty[q], radix)
}
//console.log(over);
if (!realNumber()) {
return false;
}
for (let k = 1, max2 = price.length; k < max2; k++) {
totals += (price[k] * qty[k]);
}
yes = (totals).toFixed(2);
d.g("ProductTotal").innerHTML = "$" + yes;
shipping.className = (over > 30) ? "red" : "black";
return totals;
} // end total
function checkOut() {
var retval = false;
var shippingIsRed = (shipping.className == "red");
var extraChecked = d.g("extra").checked;
if ( total() ) {
retval = (!shippingIsRed && !extraChecked)? true : false;
}
return retval;
} //end checkout
h1 {
font: 200% Arial, Helvetica;
font-weight: bold;
}
h2 {
font-weight: bold;
}
table,
td {
border: 1px solid black;
}
p.red {
color: #f00;
}
p.black {
color: #000;
}
<div>
<h1>Widgets R' Us</h1>
<h2>Order/Checkout</h2>
<form name="widgets" onsubmit="return checkOut()" action="https://www.example.com/" method="post">
<div id="mainTable">
<table>
<tr>
<td>Widget Model:</td>
<td>37AX-L
<td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$12.45 <input type="hidden" id="Price1" name="Price1" value="12.45" </td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity1" name="Quantity1" value="0" </td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>42XR-J</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$15.34 <input type="hidden" id="Price2" name="Price2" value="15.34"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity2" name="Quantity2" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Widget Model:</td>
<td>93ZZ-A</td>
</tr>
<tr>
<td>Price per Unit:</td>
<td>$28.99 <input type="hidden" id="Price3" name="Price3" value="28.99"></td>
</tr>
<tr>
<td>State:</td>
<td>Regular</td>
</tr>
<tr>
<td>Quantity:</td>
<td> <input type="text" id="Quantity3" name="Quantity3" value="0"></td>
</tr>
</table>
<tr>
<td> </td>
<td> </td>
</tr>
<table>
<tr>
<td>Total Price:</td>
<td>
<p id="ProductTotal"> 0 </p>
</td>
</tr>
<tr>
<td> <input type="checkbox" id="extra" name="extra"> </td>
<td>
<p id="shipping" class="black">If the quantity exceeds 30 units, there will be extra shipping!</p>
</td>
</tr>
</table>
</div>
<tr>
<td> <input type="Submit" value="Submit" /> </td>
<td> <input type="button" value="Calculate" onClick="total()"> </td>
</tr>
</form>
I also removed some unnecessary repetitive code that fetches the quantity values, taking advantage of JavaScript closures and for-loops.
I am trying to do a form, when you click on checkbox it has to enables the rows of the form, but it's not working...
For example, there's a checkbox above the by clicking it, it has to enable the rest of rows
I'll appreciate any help,
Thanks in advance.
Here is what I have:
<HTML>
<HEAD>
<TITLE>Online Shopping</TITLE>
<SCRIPT>
//Variables Globales
var RowsInForm = 4
var ProductsInList = 4
var SalesTaxRate = 0.12
var TaxableState = "IVA(12%)"
var ProdSubscript = 0
function MakeArray(n) {
this.length = n
for (var i = 1; i<= n; i++) {
this[i] = 0
}
return this
}
function BuildZeroArray(n) {
this.length = n
for (var i = 0; i<= n; i++) {
this[i] = 0
}
return this
}
function prodobj(name, unitprice) {
this.name = name
this.unitprice = unitprice
}
function ordobj(prodsub, qty, unitprice, extprice) {
this.prodsub = prodsub
this.qty = qty
this.unitprice = unitprice
this.extprice = extprice
}
function strToZero(anyval) {
anyval = ""+anyval
if (anyval.substring(0,1) < "0" || anyval.substring(0,1) > "9") {
anyval = "0"
}
return eval(anyval)
}
function updateRow(rownum){
var exec = 'ProdSubscript = document.ordform.prodchosen'+rownum+'.selectedIndex'
eval (exec)
ordData[rownum].prodsub=ProdSubscript
var exec='tempqty=document.ordform.qty'+rownum+'.value'
eval (exec)
ordData[rownum].qty = strToZero(tempqty)
ordData[rownum].unitprice=prodlist[ProdSubscript].unitprice
ordData[rownum].extprice = (ordData[rownum].qty) * ordData[rownum].unitprice
var exec = 'document.ordform.unitprice'+rownum+'.value = currencyPad(ordData['+rownum+'].unitprice,10)'
eval (exec)
var exec = 'document.ordform.extprice'+rownum+'.value = currencyPad(ordData['+rownum+'].extprice,10)'
eval (exec)
updateTotals()
}
function updateTotals() {
var subtotal = 0
for (var i=1; i<=RowsInForm; i++) {
subtotal = subtotal + ordData[i].extprice
}
document.ordform.subtotal.value = currencyPad(subtotal,10)
salestax = 0
if (document.ordform.Taxable.checked) {
salestax = SalesTaxRate * subtotal * 0.30
}
document.ordform.salestax.value = currencyPad(salestax,10)
document.ordform.grandtotal.value = currencyPad(subtotal+salestax,10)
}
function copyAddress() {
document.ordform.ShipName.value = document.ordform.billName.value
document.ordform.ShipCompany.value = document.ordform.billCompany.value
document.ordform.ShipAdd1.value = document.ordform.billAdd1.value
document.ordform.ShipAdd2.value = document.ordform.billAdd2.value
document.ordform.ShipCSZ.value = document.ordform.billCSZ.value
}
function currencyPad(anynum,width) {
//returns number as string in $xxx,xxx.xx format.
anynum = "" + eval(anynum)
//evaluate (in case an expression sent)
intnum = parseInt(anynum)
//isolate integer portion
intstr = ""+intnum
//add comma in thousands place.
if (intnum >= 1000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000))
temp2=intstr.substring(intlen-3,intlen)
intstr = temp1+","+temp2
}
if (intnum >= 1000000) {
intlen = intstr.length
temp1=parseInt(""+(intnum/1000000))
temp2=intstr.substring(intlen-7,intlen)
intstr = temp1+","+temp2
}
decnum = Math.abs(parseFloat(anynum)-parseInt(anynum)) //isolate decimal portion
decnum = decnum * 100 // multiply decimal portion by 100.
decstr = "" + Math.abs(Math.round(decnum))
while (decstr.length < 2) {
decstr += "0"
}
retval = intstr + "." + decstr
if (intnum < 0) {
retval=retval.substring(1,retval.length)
retval="("+retval+")"
}
retval = "BsF"+retval
while (retval.length < width){
retval=" "+retval
}
return retval
}
</SCRIPT>
</HEAD>
<BODY aLink=#8a8a8a bgColor=#ffffff
link=#ff0000 text=#000000 vLink=#215e21>
<H3 align=center><FONT color=#0000ff><FONT size=+1></FONT></FONT></H3>
<P><BR>
<SCRIPT>
//Create a new array named prodlist with six elements.
prodlist = new BuildZeroArray(ProductsInList) //Refers to global variable ProductsInList
//Populate that array with this product info.
//The first item, prodlist[0] must be a "non-product" with
//a unitprice of zero.
prodlist[0] = new prodobj('-none-',0)
prodlist[1] = new prodobj('Apple iPhone ',5200)
prodlist[2] = new prodobj('Pc Laptop',3520)
prodlist[3] = new prodobj('Impresora',4790)
prodlist[4] = new prodobj('TV',8650)
//Create a new array, named ordData, that contains empty Order Objects.
ordData = new MakeArray(RowsInForm)
for (var i=1; i<= RowsInForm; i++) {
ordData[i] = new ordobj(0,0,0,0)}
</SCRIPT>
<FORM name=ordform></P>
<CENTER>
<P><! Display the table header></P></CENTER>
<TABLE align=center border=1>
<CENTER>
<TBODY>
<TR>
<TH width=192>
<CENTER><B>Product</B></CENTER></TH>
<TH width=72>
<CENTER><B>Qty</B></CENTER></TH>
<TH width=120>
<CENTER><B>Unit Price</B></CENTER></TH>
<TH width=120>
<CENTER><B>Ext Price</B></CENTER></TH>
<P><INPUT type=checkbox value=true>
<SCRIPT>
for (var rownum = 1;rownum <= RowsInForm; rownum++) {
document.write('<TR><TD WIDTH=192>')
document.write('<SELECT NAME="prodchosen'+rownum+'" onChange= "updateRow('+rownum+')">')
for (i = 0; i <= ProductsInList; i++) {
document.write ("<OPTION>"+prodlist[i].name)
} document.write ('</SELECT>')
document.write ('</TD><TD WIDTH=72><CENTER><INPUT NAME="qty'+rownum+'" VALUE=""')
document.write ('MAXLENGTH="3" SIZE=3 onChange="updateRow('+rownum+')"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="unitprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus="this.blur()"></CENTER>')
document.write ('</TD><TD WIDTH=120><CENTER>')
document.write ('<INPUT NAME="extprice'+rownum+'" VALUE="" MAXLENGTH="10"')
document.write ('SIZE=10 onfocus = "this.blur()"></CENTER>')
document.write ('</TD></TR>')
}
</SCRIPT>
<P></P></CENTER></TBODY></TABLE>
<CENTER>
<P><! Second table holds subtotal, sales tax, grand total></P></CENTER>
<TABLE>
<TBODY>
<TR>
<TD width=264></TD>
<TD width=120>
<CENTER>
<P>Subtotal: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=subtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<P><INPUT name=Taxable onclick=updateTotals() type=checkbox value=true>
<SCRIPT>
document.write(TaxableState)
</SCRIPT>
</P></TD>
<TD width=120>
<CENTER>
<P>IVA:</P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=salestax onfocus=this.blur()
size=10></P></CENTER></TD></TR>
<TR>
<TD width=264>
<TD width=120>
<CENTER>
<P>Total: </P></CENTER></TD>
<TD width=120>
<CENTER>
<P><INPUT maxLength=10 name=grandtotal onfocus=this.blur()
size=10></P></CENTER></TD></TR></TBODY></TABLE>
<!--<P><B>Bill To:</B> <! Onto Bill To and Ship To address portions of the form></P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCompany size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billAdd2 size=50> </P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=billCSZ size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Phone:</P></TD>
<TD width=408>
<P><INPUT maxLength=25 name=Phone size=25></P></TD></TR>
<TR>
<TD width=120>
<P>Email address:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=email size=40></P></TD></TR></TBODY></TABLE>
<CENTER>
<P><INPUT onclick=copyAddress() type=button value="Copy 'Bill To' info to 'Ship To' blanks">
</P></CENTER>
<P><B>Ship To:</B> </P>
<TABLE align=center border=1>
<TBODY>
<TR>
<TD width=120>
<P>Name:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipName size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Company:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCompany size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address1:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd1 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>Address2:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipAdd2 size=50></P></TD></TR>
<TR>
<TD width=120>
<P>City, State, Zip:</P></TD>
<TD width=408>
<P><INPUT maxLength=75 name=ShipCSZ size=50></P></TD></TR></TBODY></TABLE>
<P><! In real life, you'd want to omit the whole onclick... thing in the input tag below. ><! Which is to say you want to get rid of... ><! onClick = "alert('I do not really get submitted anywhere. But thanks for trying me!')" ><INPUT onclick="alert('I do not really get submitted anywhere. But thanks for trying me!')" type=submit value=Submit>
<INPUT type=reset value=Reset> <! In real life, you can omit the entire input tag (i.e. the entire line) below ><INPUT onclick="self.location = 'jsindex.htm'" type=button value="All Done">
</FORM></P>-->
</body>
</html>
I have read this post but still have some questions. I am getting the error:
Uncaught TypeError: Cannot read property 'value' of null
On this line:
fullname = document.getElementById('namefull').value;
I am 100% sure that the field 'namefull' is on the form and I also have a value typed in the form. I actually have a check to make sure it's not null and that passes. Here is form:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
The full code is below:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<meta name="GENERATOR" content="Microsoft FrontPage 2.0">
<title>HABLA Order Form</title>
</head>
<script language="javascript">
// Do not steal, modify, or claim these scripts as your own! Thank You.
// Alterations and additions by Gordon Smith Mearns#mearns.org.uk
index = 0;
function getFields() {
fullname = document.getElementById('namefull').value;
email = document.getElementById('email').value;
phone = document.getElementById('phone').value;
zip = document.getElementById('zip').value;
amount = document.getElementById('total').value;
type = document.getElementById('order_type').value;
seller = 'TestSeller';
specinstruct = document.getElementById('specinstr').value;
xact_num = 'StripeDummy';
};
function writeXact() {
var sendtext;
getFields();
if (fullname == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
sendtext = fullname + "||" + email + "||" + phone + "||" + zip +
"||" + amount + "||" + type + "||" + seller + "||" + specinstruct +
"||" + xact_num;
xmlhttp.open("GET","writeXact.php?q="+sendtext,true);
xmlhttp.send();
}
};
function format(val, post)
{
var decpoint;
var begin;
var end;
var valstr;
var temp_char;
valstr = "" + val;
//alert('valstr = ' + valstr);
decpoint = valstr.indexOf(".")
if (decpoint != -1) {
//alert('decpoint = ' + decpoint);
begin = valstr.substring(0,decpoint);
end = valstr.substring(decpoint+1,valstr.length);
//alert('begin = ' + begin + '\nend= ' + end);
}
else {
begin = valstr;
end = "";
}
if (end.length < post)
{while (end.length < post)
{
end += "0";
}
}
end = end.substring(0,post);
//alert('begin = ' + begin + '\nend= ' + end);
return (begin+"."+end);
};
function orderSubmit(type)
{
if (type == 'order')
{if ( ! ( (document.order.order_type.checked) ||
checkRequired() ))
{document.order.form_action.value = type;
getFields();
writeXact(fullname, email, phone, zip, amount, type, seller, specinstruct, xact_num);
document.order.submit();
return true;
}
else {
// alert('first false');
return false;
}
}
};
var infowin = null;
function checkRequired() {
if (!document.order.namefull.value.length ||
!document.order.email.value.length ||
!document.order.zip.value.length ||
!document.order.phone.value.length) {
alert('You have not completed all required fields:\n' +
'Please enter Name, Email, Phone, Zip');
return true;
}
else {
return false;
}
};
<!-- -->
</script><!-- --><a name="top"></a>
<body background="images/thisback.gif" bgcolor="#FFFFFF"
text="#000000" onLoad=parent.refresh_order_details(parent.order_details) onUnload=parent.add_order_details(parent.order_details)>
<center>
<script
language="javascript">
<!-- hide
if (self==parent){document.write('<font color=#ff000><b>This is a frame element, click <a href=shopcartindex.html> here </a>for correct page</b></font>')};
<!-- end hide -->
</script>
<p><size="6" color="black" font face="Calibri"><b>HABLA Event Order Form</b><br>
</font></p>
<!-- YOU CAN PUT YOUR EMAIL ADDRESS IN THE FORM COMMAND BELOW AND THE -->
<!-- THEN IT WILL BE SENT TO YOU AS A SIMPLE MAILTO GUESTBOOK FORM -->
<!-- IF YOU DO THAT - BE SURE TO ADD THE COMMAND enctype="plain/text" -->
<!-- IN ORDER TO DELINEATE THE MAIL FOR YOU -->
<!-- YOU CAN ALSO USE TE .PL FILE AS A CGI TO HELP WTH THE MAIL. SEE THE TUTORIAL -->
<!-- FOR MORE ON HOW THAT IS DONE -->
<form action="MAILTO:hablariverglen#gmail.com" method="POST" name="order">
<input type="hidden" name="subject"
value="Order Forms - HABLA Balie 2015"><input type="hidden"
name="recipient" value="YOUR EMAIL ADDRESS HERE"><input
type="hidden" name="redirect"
value="thanku.htm"><input
type="hidden" name="retailer" value="NAME OF YOUR BUSINESS HERE"><input
type="hidden" name="form_action" value="order">
<script
language="javascript">
<!-- hide from Browsers
document.write('<table width=400><td align=center>');
document.write('<table width=400 ><tr><tr><td align=right colspan=3 ><font face="Calibri"><b>Total Purchase $</b></td><td colspan=3> <input type=text name=total font face="Calibri" value='+ format(parent.all_order_totals(),2) + '></font></td><tr>');
if (parent.items_ordered == 0)
document.write('<font color=#000080><b>There are no items in your cart<b></font>');
if (parent.item_num > 0);
{
for (i =1;i < parent.item_num;i++)
{ if (parent.itemlist[i].quan > 0)
{index = index + 1;
document.write('<input size=10 type=text font face="Calibri" name= ' + parent.itemlist[i].code + ' value= ' + parent.itemlist[i].code + '><input size=6 type=text name= ' + parent.itemlist[i].code + ' value=' + parent.itemlist[i].price + '><input size=20 type=text name= ' + parent.itemlist[i].code + ' value= '+ parent.itemlist[i].desc + '><input size=2 type=text name= ' + parent.itemlist[i].desc + ' value= '+ parent.itemlist[i].quan + '><br>');
}
}
};
<!-- end hiding -->
</script>
<!-- Customer Info Table -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Email Address:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="60" name="email"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Zip:</b></td>
<td bgcolor="#CCFFFF"><input type="text" size="9"
maxlength="10" name="zip"></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Phone:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="25" maxlength="15" name="phone"></td>
</tr>
</table>
<p align="center">
<table border="0" width=400>
<tr>
<td align="center" colspan="6"<b><font face = "Calibri"><b>Special Instructions</b><br></td>
</tr>
<tr>
<td colspan="6"><center><textarea name="specinstr" rows="3"
cols="40"></textarea></center></td>
</tr>
</table>
<!-- Order Method Table --> </p>
<table border="0" cellspacing="0" width=400>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><font
size="4"><b>Choose Order Method:</b></font></td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Credit Card: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Cash: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF">
<font size="2">Check: <input type="radio"
name="order_type" value="phone"></font> </td>
</tr>
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><a
href="options.htm" target=navigate>
</td>
</tr>
</table>
<p><br>
<p><br>
<! Stripe Credit Card Integration >
<form action="" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_zzzzzz"
data-amount="2000"
data-name="Demo Site"
data-description="2 widgets ($20.00)"
data-image="/128x128.png"
data-locale="auto">
</script>
</form>
<input
type="button" value="Place Order"
onclick="orderSubmit('order')"
<input type="reset" value="Reset Cart"> </p>
<b>HABLA Friends of River Glen <a href=mailto:hablariverglen#gmail.com>hablariverglen#gmail.com</a> </b>
</form>
</td></table>
</center>
</p>
</body >
</html>
Yes, I know the code is a mess, but I'm doing this for a school/charity fundraiser, so any help is much appreciated.
You are looking for an element with id="namefull", but in your html, you only specify the name attribute: <input type="text" size="30" maxlength="30" name="namefull">
Try including id="namefull" in here:
<input type="text" id="namefull" name="namefull" size="30" maxlength="30">
You'll want to follow suit on each of your inputs to specify the id, since that's what you're looking for with document.getElementById().
getElementById() get's an element by it's ID. You need to set the id for that to work.
Change your markup to:
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center" colspan="5" bgcolor="#CCFFFF"><b><font face = "Calibri">All Fields Required so we can contact you</b></td>
</tr>
<tr>
<td align="right" colspan="2" bgcolor="#CCFFFF"><b><font face = "Calibri">Name:</b></td>
<td colspan="3" bgcolor="#CCFFFF"><input type="text"
size="30" maxlength="30" name="namefull" id="namefull"></td>
</tr>
Notice I added id="namefull" to the input element.
I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// 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(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>
btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.
Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// 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(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>