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>
Related
I am building a mortgage calculator in Javascript. When the submit button is pressed nothing happens. I appear to have no errors in my HTML or Javascript.
function computeLoan() {
var amount = document.getElementById('amount').value;
var interest_rate =
document.getElementById('interest_rate').value;
var months = document.getElementById('months').value;
var interest = (amount * (interest_rate * .01)) / months;
var taxes = document.getElementById('taxes').value;
var insurance = document.getElementById('insurance').value;
var escrow = (taxes + insurance) / 12;
var loanPayment = amount * interest * (Math.pow(1 + interest,
months)) / (Math.pow(1 + interest, months) - 1);
var monthlyPayment = loanPayment + escrow;
monthlyPayment.toFixed(2);
monthlyPayment = document.getElementById('payment').value;
}
<form onsubmit="return computeLoan()" method="POST" action="javascript:;">
<table>
<tr>
<td class="labels">Loan Amount</td>
<td class="textbox"><input type="text" id="amount" min="1" max="10000000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Mortgage Period (months)</td>
<td class="textbox"><input type="text" id="months" min="1" max="360" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Interest Rate</td>
<td class="textbox"><input type="text" id="interest_rate" min="0" max="100" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Property Taxes</td>
<td class="textbox"><input type="text" id="taxes" min="0" max="10000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Homeowners Insurance</td>
<td class="textbox"><input type="text" id="insurance" min="0" max="10000" onchange="computeLoan()"></td>
</tr>
<tr>
<td class="labels">Monthly Payment</td>
<td class="textbox"><input type="number" id="payment" name="payment"></td>
</tr>
<tr>
<td class="button"><input type="submit" id="calculate" name="calculate" onclick="computeLoan()"></td>
<td class="button"><input type="reset" name="Reset"></td>
</tr>
</table>
</form>
I expect the textbox for Monthly Payment to populate but nothing happens.
In the computeLoan function, the last line you assign the value of your calculated field #payment (which is an empty string at this point) to the value that you just calculated before.
What you want to do is assign the calculated value monthlyPayment to the value property of the input#payment element.
So revert the assignment in the last line
monthlyPayment = document.getElementById('payment').value;
should become
document.getElementById('payment').value = monthlyPayment;
Additionally you are also executing the function multiple times.
The onsubmit of the form executes the function
The onclick of the submit button executes the function
Considering the action of the form you are not submitting the form, so you could reduce the code to
function computeLoan() {
var amount = document.getElementById('amount').value;
var interest_rate =
document.getElementById('interest_rate').value;
var months = document.getElementById('months').value;
var interest = (amount * (interest_rate * .01)) / months;
var taxes = document.getElementById('taxes').value;
var insurance = document.getElementById('insurance').value;
var escrow = (taxes + insurance) / 12;
var loanPayment = amount * interest * (Math.pow(1 + interest,
months)) / (Math.pow(1 + interest, months) - 1);
var monthlyPayment = loanPayment + escrow;
monthlyPayment.toFixed(2);
document.getElementById('payment').value = monthlyPayment;
}
<form onsubmit="return false;">
<table>
<tr>
<td class="labels">Loan Amount</td>
<td class="textbox">
<input type="text" id="amount" min="1" max="10000000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Mortgage Period (months)</td>
<td class="textbox">
<input type="text" id="months" min="1" max="360" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Interest Rate</td>
<td class="textbox">
<input type="text" id="interest_rate" min="0" max="100" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Property Taxes</td>
<td class="textbox">
<input type="text" id="taxes" min="0" max="10000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Homeowners Insurance</td>
<td class="textbox">
<input type="text" id="insurance" min="0" max="10000" onchange="computeLoan()">
</td>
</tr>
<tr>
<td class="labels">Monthly Payment</td>
<td class="textbox">
<input type="number" id="payment" name="payment">
</td>
</tr>
<tr>
<td class="button">
<button id="calculate" name="calculate" onclick="computeLoan()">
Calculate
</button>
</td>
<td class="button">
<input type="reset" name="Reset">
</td>
</tr>
</table>
</form>
Note that the button is not a submit anymore. And that the form is prevented its default action on submit only.
Additionally you can make the computateLoan only compute something when all values are defined
function computeLoan() {
const amount = document.getElementById('amount').value;
const interest_rate = document.getElementById('interest_rate').value;
const months = document.getElementById('months').value;
// This `let result = value1 || value2` is similar to the trenary operator
// `let result = value1 ?: value2` you might know from other labguages
// `result` will evaluate to `value1` if that is not null or undefined,
// otherwise it will evaluate to `value2`
const taxes = document.getElementById('taxes').value || 0;
const insurance = document.getElementById('insurance').value || 0;
if (amount && interest_rate && months) {
let interest = (amount * (interest_rate * .01)) / months;
let escrow = (taxes + insurance) / 12;
let loanPayment = amount * interest * (Math.pow(1 + interest, months)) / (Math.pow(1 + interest, months) - 1);
let monthlyPayment = (loanPayment + escrow).toFixed(2);
document.getElementById('payment').value = monthlyPayment;
} else {
document.getElementById('payment').value = '';
}
}
See: https://codepen.io/anon/pen/ROENKW
function computeLoan() {
// rest of the function
var monthlyPayment = loanPayment + escrow;
monthlyPayment = monthlyPayment.toFixed(2);
document.getElementById('payment').value = monthlyPayment;
}
Hey please update the last two lines of the function by assigning the value of monthlyPayment to the element.
This will work :)
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
I was able to create the template, but I'm not sure what to do from here.
When I click my add item button, I want the values to go into the text area I created on the bottom and change the subtotal and total as I keep adding items.
<html>
<head>
<meta charset = "utf-8">
<h1>Invoice Manager</h1>
<style type "text/css">
div {position: absolute;
top: 200px;
left: 90px;
z-index: 1;}
</style>
<script type = "text/javascript">
</script>
</head>
<body>
<table>
<tr>
<td align="right">Item Code:</td>
<td align="left"><input type="text" name="code" /></td>
</tr>
<tr>
<td align="right">Item Name:</td>
<td align="left"><input type="text" name="itemName" /></td>
</tr>
<tr>
<td align="right">Item Cost:</td>
<td align="left"><input type="text" name="cost" /></td>
</tr>
<tr>
<td align="right">Quantity:</td>
<td align="left"><input type="text" name="quantity" /></td>
</tr>
</table>
<div id="AddItemButton">
<td align = "left"><input type="submit" name="Submit" value="Add Item"></td>
</div>
</form>
<br></br> <br></br>
<font size = "5">Current Invoice</font>
<hr style = "height:2px;border:none;color:#333;background-color:#333;"></hr>
<p><label> <br>
<textarea name = "textarea"
rows = "12" cols = "180"></textarea>
</label></p>
<form>
<table>
<tr>
<td align="right">Subtotal:</td>
<td align="left"><input type="text" name="subtotal" /></td>
</tr>
<tr>
<td align="right">Sales Tax:</td>
<td align="left"><input type="text" name="tax" /></td>
</tr>
<tr>
<td align="right">Total:</td>
<td align="left"><input type="text" name="total" /></td>
</tr>
</table>
</form>
<form>
<input type = "button" value = "Add Item" onclick="textarea"/> <input type = "text" id = "cost" size ="20" />
</form>
That's what I have as a template. When I type in Item Code, Item Name, Item Cost and Quantity in those fields, I'd like those values to go in the text area on the bottom. I imagine I would need to write something in the script.
I'm not sure how to achieve this, but I was thinking that the first batch of info the user adds could equal a variable like a
Then the second values inputted could equal b
So let's say the user adds 3 items.
total = (a + b + c)
Or something like that.
Here's an example of what one "Add Item" would do. I'd like these submissions to appear in the text field I created like so
---Item Code--- ---Item Name--- ---Item Cost--- ---Quantity---
3 Dell 499 1
Any ideas on what I could do? I'm at a loss
Thanks
EDIT: I'm adding my script, I'm wondering if there's something wrong with it
<script type = "text/javascript">
function computeCost(){
var code = document.getElementById("code").value;
var a = code; // item code
var itemName = document.getElementById("itemName").value;
var b = itemName; // item name
var cost = document.getElementById("cost").value;
var c = cost; // calculate cost
var quantity = document.getElementById("quantity").value;
var d = quantity; // calculate quantity of items
var subtotal = document.getElementById("subtotal").value;
var e = c * d; // multiplying cost by quantity = subtotal
var tax = document.getElementById("tax").value;
var f = e * .7; // multiplying subtotal by tax(.7) = amount of tax owed
var total = document.getElementById("total").value;
var g = f + e; //adding tax to subtotal = total value
document.getElementByID("yo").value = total;
}
function clear()
{
document.getElementById("a","b","c","d", "e", "f", "g").reset();
} // end of clear
</script>
I dont have much time to give a polished script, but this provides basic functionality
EDIT: added script tags and basic JQUERY things
note that because of loading JQUERY from the internet, it wont work without internet connection, if you wish to use it without internet con, download the script and link it locally
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type = "text/javascript">
$(function(){
var textContent = $('textarea').val();
var textRow = "";
$('input[type=submit]').click(function(){
$('input[type=text]').each(function(){
textRow = textRow+$(this).val()+'\t';
});
textContent = textContent + '\n' + textRow;
textRow = "";
$('textarea').val(textContent);
});
});
</script>
this is just the necessary JS and HTML, nothing fancy:
function id(id){return document.getElementById(id);}
var val1 = 0;
var val2 = 0;
function val(){
val1 = parseInt(id("t1").value);
val2 = parseInt(id("t2").value);
id("total").innerHTML = ((val1 > 0 && val2 > 0))? val1 * val2 : 0;
}
<input id="t1" onkeyup="val()" type="number">
<input id="t2" onkeyup="val()" type="number">
<h1 id="total"></h1>
I have a problem with the following JavaScript code. It has an error alert said that table value is undefined. I'm trying to update the subtotal in each row by calculate price * qty.
function updateSubtotal() {
var subTotal = 0;
var tables = document.getElementsByTagName("table").rows;
var r = this.parentNode.parentNode.rowIndex;
var j = document.getElementsByTagName(".price").cellIndex;
var s = document.getElementsByTagName(".subtotal").cellIndex;
var price = tables[r].cells[j].value;
var quantity = document.getElementsByTagName("input").value;
var subAmount = price * quantity;
subTotal += Number(subAmount);
// set total for the row
document.getElementsByTagName('table').rows[r].cells[s].innerHTML = '$' + subTotal.toFixed(2);
}
updateTotal();
}
The original code that I tried to update:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
window.onload = setupCart;
function setupCart() {
var qtyInputs = document.querySelectorAll( 'input' );
for ( var i = 0; i < qtyInputs.length; i++ ) {
qtyInputs[ i ].oninput = updateSubtotal;
}
updateTotal();
}
function updateTotal() {
var total = 0;
var subTotals = document.querySelectorAll( '.subtotal' );
for ( var i = 0; i < subTotals.length; i++ ) {
var amount = subTotals[ i ].innerHTML.match( /[0-9]+.[0-9]+/ );
total += Number( amount );
}
document.querySelector( '#total' ).innerHTML = '$' + total.toFixed( 2 );
}
</script>
</head>
<body>
><table>
><tr>
><th>Description</th>
><th>Each</th>
><th>Qty</th>
><th>subtotal</th>
></tr>
<tr class="item">
<td class="description"><img src="red-shirt.jpg" alt="" />Red Crew Neck T-Shirt</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="item">
<td class="description"><img src="tropical-shirt.jpg" alt="" />Blue Tropical Floral Print T-Shirt</td>
<td class="price">$25.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$25.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sneakers.jpg" alt="" />Black Canvas Lace Up Sneakers</td>
<td class="price">$35.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$35.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-grey-jacket.jpg" alt="" />Black and Grey Hooded Jacket</td>
<td class="price">$40.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$40.00</td>
</tr>
<tr class="item">
<td class="description"><img src="black-sunglasses.jpg" alt="" />Black Retro Sunglasses</td>
<td class="price">$15.00</td>
<td><input type="number" value="1" min="0" /></td>
<td class="subtotal">$15.00</td>
</tr>
<tr class="cart-summary">
<td></td>
<td></td>
<th>Total:</th>
<td id="total"></td>
</tr>
</table>
</body>
</html>
The .getElementsByTagName() function returns a NodeList object. If you want the first <table> on the page, you'd use
document.getElementsByTagName("table")[0].rows ...
It would be better to fetch it just once at the start of the function:
var table = document.getElementsByTagName("table")[0];
to avoid having to re-traverse the DOM.
Maybe it's because document.getElementsByTagName doesn't return an element but a list of elements... you have to access the node you need like this document.getElementsByTagName("table")[0].rows
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>