Trouble with updating an HTML table using javascript - javascript

I looked through a few questions on here but none of them seems to be showing the problem that I am having.
The Problem:
I have a business case question where we are asked to build a simple calculator for a business pricing model using HTML/Javascript/CSS.
I'm still a beginner to these languages but have good experience in other languages.
I have been through google and stack overflow, all of which are telling me to use the "document.GetElementById()" function.
I have tried implementing this function however I must be doing something wrong because when I press submit nothing happens.
I apologise for the following being a long code block but I can't be sure where my error actually is.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
<script>
function displayTable() {
let boxStr = document.getElementById("number");
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
prices = bracket1(numOfEmps);
case numOfEmps <= 50:
prices = bracket2(numOfEmps);
case numOfEmps <= 250:
prices = bracket3(numOfEmps);
}
document.getElementById("mojo-price").innerHTML = String(prices[0]);
document.getElementById("wiredup-price").innerHTML = String(prices[1]);
document.getElementById("workwith-price").innerHTML = String(prices[2]);
document.getElementById("063-price").innerHTML = String(prices[3]);
document.getElementById("total-price").innerHTML = String(prices[4]);
function bracket1(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 75;
let workWith = numOfEmps * 75;
let the063 = numOfEmps * 250;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket2(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 60;
let workWith = numOfEmps * 60;
let the063 = numOfEmps * 200;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket3(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 54;
let workWith = numOfEmps * 54;
let the063 = numOfEmps * 180;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
}
</script>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>
What I am hoping happens is that the table is populated with the calculated prices correctly.
I will be dealing with the CSS side of the question once the functionality works.

You were not defining prices before using it and you were reading the reference to the input element itself, not its value (document.getElementById("number").value).
Here you go:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
<script>
function displayTable() {
let prices = []
let boxStr = document.getElementById("number").value
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
prices = bracket1(numOfEmps);
case numOfEmps <= 50:
prices = bracket2(numOfEmps);
case numOfEmps <= 250:
prices = bracket3(numOfEmps);
}
document.getElementById("mojo-price").innerHTML = String(prices[0]);
document.getElementById("wiredup-price").innerHTML = String(prices[1]);
document.getElementById("workwith-price").innerHTML = String(prices[2]);
document.getElementById("063-price").innerHTML = String(prices[3]);
document.getElementById("total-price").innerHTML = String(prices[4]);
}
function bracket1(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 75;
let workWith = numOfEmps * 75;
let the063 = numOfEmps * 250;
let totalPrice = mojo + wiredUp + workWith + the063;
console.log(numOfEmps)
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket2(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 60;
let workWith = numOfEmps * 60;
let the063 = numOfEmps * 200;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket3(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 54;
let workWith = numOfEmps * 54;
let the063 = numOfEmps * 180;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
</script>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>
A hint I would give you is to console.log() (a.k.a. print) everything to understand the state of your data. Modern browses also have very powerful JavaScript debuggers too, so you can use breakpoints, print objects as tables, edit values during execution and all that. For Firefox and Chrome you can call it with Ctrl + Shift + I.

You dont have to use String constructor. innerHTML can contains both numbers and strings. Also, you can use textContent cause you don't insert any of html in there. As previous answers said, you haven't ever define prices.
Check html5 input docs. There are many arguments that can help you to control over the input values or validation. As you can see required attribute for input prevents of living this field empty and type number is tell that this field accept only numbers. Also there are min and max attributes< I guess you find out what they do)
let prices = {
mojo: {
coefs: {
1: 0,
2: 0,
3: 0
},
price: 0
},
wiredup: {
coefs: {
1: 75,
2: 60,
3: 54
},
price: 0
},
workwith: {
coefs: {
1: 75,
2: 60,
3: 54
},
price: 0
},
the063: {
coefs: {
1: 200,
2: 250,
3: 180
},
price: 0
}
}
let totalPrice = getTotalPrice()
const numberEl = document.querySelector('#number')
setTableValues()
function displayTable() {
let value = numberEl.value
if (value <= 12) {
getPriceForBracket(value, 1);
} else if (value <= 50) {
getPriceForBracket(value, 2)
} else if (value <= 250) {
getPriceForBracket(value, 3)
}
setTableValues()
}
function getPriceForBracket(value, bracket) {
Object.keys(prices).forEach(key => {
prices[key].price = value * prices[key].coefs[bracket]
})
}
function getTotalPrice() {
return Object.values(prices).reduce((res, val) => res + val.price, 0)
}
function setTableValues() {
Object.keys(prices).forEach(key => {
document.querySelector(`#${key}-price`).textContent = prices[key].price
document.querySelector('#total-price').textContent = getTotalPrice()
})
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="number" placeholder="30" id="number" value="1" min="0" max="9999" required>
</form>
<button type="button" onclick="displayTable()">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="the063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>

Telmo's answer addresses the core of your problem, and he should get the accepted tick IMO. I've just refactored it down to reduce the amount of repeated code. I've used a couple of objects, one to store the brackets and another to store the final prices.
const brackets = {
one: {
mojo: 0,
wiredUp: 75,
workWith: 75,
the063: 250
},
two: {
mojo: 0,
wiredUp: 60,
workWith: 60,
the063: 200
},
three: {
mojo: 0,
wiredUp: 54,
workWith: 54,
the063: 180
}
}
function displayTable() {
let prices = {
"mojo": "",
"wiredUp": "",
"workWith": "",
"Zero63": "",
"total": ""
};
let bracket = {};
let boxStr = document.getElementById("number").value
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
bracket = brackets.one
case numOfEmps <= 50:
bracket = brackets.two
case numOfEmps <= 250:
bracket = brackets.three
}
prices.mojo = bracket.mojo;
prices.wiredUp = numOfEmps * bracket.wiredUp;
prices.workWith = numOfEmps * bracket.workWith;
prices.Zero63 = numOfEmps * bracket.the063;
prices.total = prices.mojo + prices.wiredUp + prices.workWith + prices.Zero63;
document.getElementById("mojo-price").textContent = String(prices.mojo);
document.getElementById("wiredup-price").textContent = String(prices.wiredUp);
document.getElementById("workwith-price").textContent = String(prices.workWith);
document.getElementById("063-price").textContent = String(prices.Zero63);
document.getElementById("total-price").textContent = String(prices.total);
}
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>

Related

How i want to write function when i click on button calculate order, it will show the ouput

The cleaning total I got is from total laundry.
I have written the function for calculate tax amount and total order amount. but I'm not sure which line got error. It's more confusing when I only can use one button (calculate order) for 2 function.
function calculateTaxAmount() {
let cleaningTotal = document.getElementById("cleaningTotal");
let tax = 5.75;
let taxAmount = cleaningTotal * tax / 100;
document.getElementById("taxAmount").value = taxAmount;
}
function processOrder() {
var f1 = document.getElementById('sum').value;
var f2 = document.getElementById('sumpants').value;
var f3 = document.getElementById('sumItem1').value;
var f4 = document.getElementById('sumItem2').value;
var f5 = document.getElementById('sumItem3').value;
var f6 = document.getElementById('sumItem4').value;
if (f1 == "") f1 = 0;
if (f2 == "") f2 = 0;
if (f3 == "") f3 = 0;
if (f4 == "") f4 = 0;
if (f5 == "") f5 = 0;
if (f6 == "") f6 = 0;
var result = parseInt(f1) + parseInt(f2) + parseInt(f3) + parseInt(f4) + parseInt(f5) + parseInt(f6);
if (!isNaN(result)) {
document.getElementById('cleaningTotal').value = result;
}
var orderTotal = cleaningTotal + tax; {
document.getElementById('orderTotal').value = result
}
}
<input type="button" value="Calculate Order" onclick="processOrder()"><br><br>
<label>Cleaning Total</label>
</td>
<td>
<div>
<input type="text" name="cleaningTotal" id="cleaningTotal" value="">
</div>
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Tax Rate</label>
</td>
<td>
<input type="text" name="taxRate" id="taxRate" value="5.75">%
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Tax Amount : </label>
</td>
<td>
<div>
<input type="text" name="taxAmount" id="taxAmount" onclick="processOrder()" value="">
</div>
</td>
<td> </td>
</tr>
<tr class="tbl-foot">
<td colspan="3">
<label>Order Total : </label>
</td>
<td>
<div>
<input type="text" name="orderTotal" id="orderTotal" value="">
</div>
</td>
<td> </td>
</tr>

How to reset my weekly loan calculation to 0 and take another loan weekly loan payment?

Right now i am working on a loan page and it is almost finished. Can someone tell me how to reset my repay form when i make a new loan if my current loan have been fully paid. I created function. The first one is to calculate the loan amount, weekly loan amount and weekly period amount to pay the loan.
Here is the HTML page:
<div id="loanpage">
<form id="loanform">
<h3>Loan Calculator</h3>
<table>
<tr>
<td>Loan amount required</td>
<td>
<input type="text" min="100" max="100,000" id="loanamount" autocomplete="off" required placeholder="Max 100,000" />
</td>
</tr>
<tr>
<td>currency</td>
<td>
<select name="currency" value="currency" id="currency">
<option id="currency1"></option>
<option id="currency2"></option>
<option id="currency3"></option>
<option id="currency4"></option>
<option id="currency5"></option>
</select>
</td>
</tr>
<tr>
<td>Repayment period in years</td>
<td>
<input type="text" min="1" max="5" id="period" autocomplete="off" placeholder="Max 5 years" />
</td>
</tr>
<tr>
<td>Interest p.a. </td>
<td>
<input type="text" value="5%" disabled id="interest" />
</td>
</tr>
<tr>
<td>
<input type="button" value="Calculate weekly instalment" class="btn btn-success" onclick="loanForm();" />
</td>
</tr>
<tr>
<td>Total amount payable</td>
<td>
<input type="text" disabled id="payableloan" />
</td>
</tr>
<tr>
<td>Weekly instalment amount</td>
<td>
<input type="text" disabled id="weeklyloan" />
</td>
</tr>
<tr>
<td>Number of instalments</td>
<td>
<input type="text" disabled id="numberInstalment" />
</td>
</tr>
</table>
</form>
<div id="repayform">
<h3>Loan payment</h3>
<form>
<table>
<tr>
<td>Total amount payable</td>
<td>
<input type="text" id="repayamount" disabled autocomplete="off" />
</td>
</tr>
<tr>
<td>Total instalments paid</td>
<td>
<input type="text" name="paidloan" disabled id="amountPaid" />
</td>
</tr>
<tr>
<td>Loan balance payable</td>
<td>
<input type="text" disabled name="paidloan" id="currentBalance" />
</td>
</tr>
<tr>
<td>Instalment amount due</td>
<td>
<input type="text" disabled name="paidloan" id="due" />
</td>
</tr>
<tr>
<td>
<input type="button" class="btn btn-success" id="paybtn" onclick="payNow()" value="Pay now" />
</td>
</tr>
</table>
</form>
</div>
</div>
Here is my javascript file:
let loanInterestRate = 5;
let principal = document.getElementById("loanamount").value;
let userCurrency = document.getElementById("currency").value;
let loanPeriod = document.getElementById("period").value;
let interestTotal = (loanInterestRate / 100) * loanPeriod + 1;
let loanAmountPayable = principal * interestTotal;
let loanPeriodInWeeks = loanPeriod * 52;
let weeklyInstalment = loanAmountPayable / loanPeriodInWeeks;
let instalmentPaidTotal = 0;
let payButton = document.getElementById("paybtn");
function loanForm() {
principal = document.getElementById("loanamount").value;
userCurrency = document.getElementById("currency").value;
loanPeriod = document.getElementById("period").value;
interestTotal = (loanInterestRate / 100) * loanPeriod + 1;
loanAmountPayable = principal * interestTotal;
loanPeriodInWeeks = loanPeriod * 52;
weeklyInstalment = loanAmountPayable / loanPeriodInWeeks;
document.getElementById("payableloan").value = userCurrency + " " + loanAmountPayable.toFixed(2);
document.getElementById("weeklyloan").value = userCurrency + " " + weeklyInstalment.toFixed(2);
document.getElementById("numberInstalment").value = loanPeriodInWeeks + " weeks";
document.getElementById("repayamount").value = userCurrency + " " + loanAmountPayable.toFixed(2);
document.getElementById("due").value = userCurrency + " " + weeklyInstalment.toFixed(2);
}
function payNow() {
instalmentPaidTotal = weeklyInstalment + instalmentPaidTotal;
let loanBalancePayable = loanAmountPayable - instalmentPaidTotal;
if (loanBalancePayable > 0) {
document.getElementById("amountPaid").value =
userCurrency + " " + instalmentPaidTotal.toFixed(2);
document.getElementById("currentBalance").value =
userCurrency + " " + loanBalancePayable.toFixed(2);
} else {
alert("You loan account is 0");
}
}
Any help and suggestion is appreciated and welcomed.
By looks of it, you can do two things to reset.
JavaScript Variables Reset
HTML Form Reset
Both the above can be done using JavaScript. What you need to do is:
// Since a few things are dependent on the form values, first reset the form.
document.getElementById("loanform").reset();
// JavaScript Variables Reset.
// Reset to the initialisation data.
loanInterestRate = 5;
principal = document.getElementById("loanamount").value;
userCurrency = document.getElementById("currency").value;
loanPeriod = document.getElementById("period").value;
interestTotal = (loanInterestRate / 100) * loanPeriod + 1;
loanAmountPayable = principal * interestTotal;
loanPeriodInWeeks = loanPeriod * 52;
weeklyInstalment = loanAmountPayable / loanPeriodInWeeks;
instalmentPaidTotal = 0;
The above should work. Let me know if there's any question.
A best way is to have the above in a function:
function init() {
// Since a few things are dependent on the form values, first reset the form.
document.getElementById("loanform").reset();
// JavaScript Variables Reset.
// Reset to the initialisation data.
loanInterestRate = 5;
principal = document.getElementById("loanamount").value;
userCurrency = document.getElementById("currency").value;
loanPeriod = document.getElementById("period").value;
interestTotal = (loanInterestRate / 100) * loanPeriod + 1;
loanAmountPayable = principal * interestTotal;
loanPeriodInWeeks = loanPeriod * 52;
weeklyInstalment = loanAmountPayable / loanPeriodInWeeks;
instalmentPaidTotal = 0;
}
// Call the function...
init();
You may name the above function as init() or reset() as per your convenience.

Javascript form not returning a result when submit button is pressed

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 :)

Error within HTML Code

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.

HTML table <td> linked to Javascript how?

I have an order form within an HTML table associated to some JavaScript verification logic. The current code works but I would like some enhancements to be implemented.
Currently, pressing the "verify" order button gives me the following output:
Line 0 = 1 Qty Line 1 = 4 Qty Line 2 = 2 Qty
Instead of showing table lines numbers followed by quantity value, I need the text to contain the actual products names. E.g. "Line 0 = 1" → "Apple = 1" …
I cannot really seem to figure it out can someone tell me how to do this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<SCRIPT LANGUAGE="javascript" TYPE="text/javascript">
<!-- Original: Mike McGrath (mike_mcgrath#example.net) -->
<!-- Web Site: http://website.example.net/~mike_mcgrath/ -->
<!--
function count(f, n, u) {
f.line_sum[n].value = f.line[n].value * u;
f.line_sum[n].value = Math.ceil(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.floor(f.line_sum[n].value * 1000) / 1000;
f.line_sum[n].value = Math.round(f.line_sum[n].value * 100) / 100;
if (f.line_sum[n].value == "NaN") {
alert("Error:\nYou may only enter numbers...\nPlease retry");
f.line[n].value = f.line[n].value.substring(0, f.line[n].value.length - 1);
f.line_sum[n].value = f.line[n].value * u;
if (f.line_sum[n].value == "0") f.line_sum[n].value = "";
} else {
var gt = 0;
for (i = 0; i < f.line_sum.length; i++) {
gt += Math.ceil(f.line_sum[i].value * 1000) / 1000;
}
gt = Math.round(gt * 1000) / 1000;
f.grand_total.value = "$ " + gt;
decimal(f);
}
}
function get_data(f) {
var order_data = "This Order is ...\n";
for (i = 0; i < f.line.length; i++) {
if (f.line[i].value == "") f.line[i].value = "0";
order_data += "Line " + i + " = " + f.line[i].value + " Qty\n";
}
if (f.grand_total.value == "") f.grand_total.value = "Nil";
order_data += "Total Order Value = " + f.grand_total.value;
document.g.order.value = order_data;
}
function decimal(f) {
for (i = 0; i < f.line_sum.length; i++) {
var d = f.line_sum[i].value.indexOf(".");
if (d == -1 && f.line[i].value != 0) f.line_sum[i].value += ".00";
if (d == (f.line_sum[i].value.length - 2)) f.line_sum[i].value += "0";
if (f.line_sum[i].value == "00") f.line_sum[i].value = "";
}
d = f.grand_total.value.indexOf(".");
if (d == -1) f.grand_total.value += ".00";
if (d == (f.grand_total.value.length - 2)) f.grand_total.value += "0";
}
function send_data(g) {
get_data(document.f);
if (document.f.grand_total.value == "Nil") {
var conf = confirm("No items are entered - \nDo you want to submit a blank order?");
if (conf) g.submit();
else init();
} else g.submit();
}
function init() {
document.f.reset();
document.f.line[0].select();
document.f.line[0].focus();
document.g.order.value = "";
}
window.onload = init;
// -->
</SCRIPT>
</head>
<body>
<FORM NAME="f">
<TABLE BGCOLOR="mistyrose" BORDER="2" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD COLSPAN="4" ALIGN="center">
<B>Order Form</B>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<U>Item</U>
</TD>
<TD>
<U>Qty</U>
</TD>
<TD>
<U>Each</U>
</TD>
<TD ALIGN="right">
<U>Total</U>
</TD>
</TR>
<TR>
<TD>Apple</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,0,5.95)">
</TD>
<TD>$ 5.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>Banana</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,1,10.95)">
</TD>
<TD>$ 10.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD>Orange</TD>
<TD>
<INPUT NAME="line" TYPE="text" SIZE="5" VALUE="" ONKEYUP="count(this.form,2,20.95)">
</TD>
<TD>$ 20.95</TD>
<TD ALIGN="right">
<INPUT NAME="line_sum" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR BGCOLOR="beige">
<TD>
<INPUT TYPE="button" VALUE="Reset" ONCLICK="init()">
</TD>
<TD COLSPAN="2" ALIGN="right">
<U>Grand Total :</U>
</TD>
<TD ALIGN="right">
<INPUT NAME="grand_total" TYPE="text" SIZE="10" READONLY>
</TD>
</TR>
<TR>
<TD COLSPAN="4" ALIGN="center">
<INPUT TYPE="button" VALUE="Press to Verify Order" ONCLICK="get_data(this.form)">
</TD>
</TR>
</TBODY>
</TABLE>
</FORM>
<FORM NAME="g" METHOD="post" ENCTYPE="text/plain" ACTION="mailto:user#isp">
<TABLE BGCOLOR="cadetblue" BORDER="4" WIDTH="320" CELLPADDING="5" CELLSPACING="0" SUMMARY="">
<TBODY>
<TR>
<TD ALIGN="center">
<TEXTAREA NAME="order" ROWS="5" COLS="35">
</body>
</html>

Categories