Javascript Function Displays NaN - javascript

I am new to Javascript and am taking a course in which I must write a script that computes a maximum affordable housing payment. I'm stuck, as the calculation keeps returning NaN. Again, this is very basic script, and I am just trying to learn and figure out what I'm doing wrong, so please don't be overcritical. I am planning to add in the CSS/styling once I get this part figured out. Here is the code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Affordable House Payment</title>
<script type="text/javascript">
function doWork()
{
var income = +document.getElementById("monthly_income") + document.getElementById("alimony_income") + document.getElementById("interest_income");
var expenses = +document.getElementById("credit_card") + document.getElementById("car_payments") + document.getElementById("other_paments");
x = .29 * incom;
y = .39 * income;
z = y - expenses;
if (z < x)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
else if (x < z)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + x + " per month. This number was calculated by taking 29% of your Gross Income.";
}
else
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>
</head>
<body>
<h1>Maximum Affordable House Payment</h1>
<p>To calculate your maximum affordable house payment, input your information below and click Submit:</p>
<form id="afford" onsubmit="return doWork()">
<fieldset form="afford">
<legend>Income</legend>
<label for="monthly_income">Monthly Income</label>
<input type="number" id="monthly_income" />
<label for="alimony_income">Alimony Income</label>
<input type="number" id="alimony_income" />
<label for="interest_income">Interest/Dividend Income</label>
<input type="number" id="interest_income" />
</fieldset>
<br />
<fieldset form="afford">
<legend>Expenses</legend>
<label for="credit_card">Credit Card Payments</label>
<input type="number" id="credit_card" />
<label for="car_payments">Car Payments</label>
<input type="number" id="car_payments" />
<label for="other_payments">Other Recurring Payments</label>
<input type="number" id="other_payments" />
</fieldset>
<input id="submit" type="submit" value="Submit" />
</form>
<p id="result"></p>
</body>
</html>
EDIT:
#Ted Here is my revised script. Now the calculation does not display whatsoever, so hard to say if it is outputting a number.
<script type="text/javascript">
function doWork()
{
var income = parseFloat(document.getElementById("monthly_income").value) + parseFloat(document.getElementById("alimony_income").value) + parseFloat(document.getElementById("interest_income").value);
var expenses = parseFloat(document.getElementById("credit_card").value) + parseFloat(document.getElementById("car_payments").value) + parseFloat(document.getElementById("other_paments").value);
x = .29 * income;
y = .39 * income;
z = y - expenses;
if (z < x)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
else if (x < z)
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + x + " per month. This number was calculated by taking 29% of your Gross Income.";
}
else
{
document.getElementById("result").innerHTML = "Your maximum affordable house payment is " + z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>

In your code:
function doWork()
{
var income = +document.getElementById("monthly_income") + document.getElementById("alimony_income") + document.getElementById("interest_income");
It is much simpler to get a reference to the form and access the controls by named properties of the form. The reference can be passed from the listener. Also, you are getting references to the controls, what you want are the values, e.g.
<form onsubmit="return doWork(this);" ...>
And the function:
function doWork(form) {
var income = +form.monthly_income.value + +form.alimony_income.value +
+form.interest_income.value;
var expenses = +form.credit_card.value + +form.car_payments.value +
+form.other_paments.value;
You shoud also keep variables local with var:
var x = .29 * income;
var y = .39 * income;
var z = y - expenses;
And keep a reference to the output element rather than all that typing:
var outputElement = document.getElementById("result");
if (z < x) {
outputElement.innerHTML = ...
} else if (...) {
...
Don't give any form control a name or ID of "submit" as it will mask the form's submit method so it can't be called. The submit button could just be a plain button that calls the function, no need to submit the form and its value should be something like "Calculate".
There were also a number of typos in the code, here it is cleaned up a bit. It still needs work though.
<script>
function doWork(form) {
var income = +form.monthly_income.value + +form.alimony_income.value +
+form.interest_income.value;
var expenses = +form.credit_card.value + +form.car_payments.value +
+form.other_payments.value;
var x = .29 * income;
var y = .39 * income;
var z = y - expenses;
var outputElement = document.getElementById("result");
if (z < x) {
outputElement.innerHTML = "Your maximum affordable house payment is " +
z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
} else if (x < z) {
outputElement.innerHTML = "Your maximum affordable house payment is " +
x + " per month. This number was calculated by taking 29% of your Gross Income.";
} else {
outputElement.innerHTML = "Your maximum affordable house payment is " +
z + " per month. This number was calculated by taking 39% of your Gross Income, less Expenses.";
}
return false;
}
</script>
<h1>Maximum Affordable House Payment</h1>
<p>To calculate your maximum affordable house payment, input your information below and click Submit:</p>
<form id="afford" onsubmit="return doWork(this);">
<fieldset form="afford">
<legend>Income</legend>
<label for="monthly_income">Monthly Income
<input type="number" name="monthly_income"></label>
<label for="alimony_income">Alimony Income
<input type="number" name="alimony_income"></label>
<label for="interest_income">Interest/Dividend Income
<input type="number" name="interest_income"></label>
</fieldset>
<br>
<fieldset form="afford">
<legend>Expenses</legend>
<label for="credit_card">Credit Card Payments
<input type="number" name="credit_card"></label>
<label for="car_payments">Car Payments
<input type="number" name="car_payments"></label>
<label for="other_payments">Other Recurring Payments
<input type="number" name="other_payments"></label>
</fieldset>
<input type="submit" value="Calculate">
</form>
<p id="result"></p>

You can't just add the DOM elements; you need to add the values currently in the elements. Also, you want to add integers, not concatenate strings, so you really need:
parseFloat(document.getElementById("monthly_income").value)
etc. instead of
+document.getElementById("monthly_income")

Related

Simple Calculator Test

When I process my code in the browser all I get is this:
I use the following code that does not work as intended:
function compute() {
p=document.getElementById("principal").value;
r=document.getElementById("rate").value;
n=document.getElementById("years").value;
result=document.getElementById("result");
result.innerHTML="If you deposit " + p + ",";
result.innerHTML="at an interest rate of " + r + ".";
result.innerHTML="in the year " + (newDate - n);
result.innerHTML="You will receive an amount of " + (p*n*r/100) + ",";
}
With a small number of modifications, the compute function should work very well.
The changes:
Ensure all our input values are converted to numbers.
Create a result output element (id="result") to show the results.
Append output to result string, then assign this to result element innerHTML.
Create getFutureValue function to get total amount after n years.
function getFutureValue(principal, interestRatePercent, termYears) {
return principal*Math.pow(1 + interestRatePercent/100, termYears);
}
function showResult(result) {
document.getElementById("result").innerHTML = result;
}
function compute() {
// Ensure all values are _numbers_
p = Number(document.getElementById("principal").value);
r = Number(document.getElementById("rate").value);
n = Number(document.getElementById("years").value);
const newDate = new Date();
newDate.setFullYear(newDate.getFullYear() + n);
let result = "If you deposit $" + p + ", ";
result += "at an interest rate of " + r + "%, ";
result += "in the year " + (newDate.getFullYear());
result += ", you will receive an amount of $" + getFutureValue(p, r, n).toFixed(2);
showResult(result);
}
compute()
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css">
<form class="p-3">
<div class="mb-3">
<label for="principal" class="form-label" >Amount</label>
<input type="number" class="form-control" id="principal" value="1000">
</div>
<div class="mb-3">
<label for="rate" class="form-label">Interest Rate</label>
<input type="number" class="form-control" id="rate" value="3.5">
</div>
<div class="mb-3">
<label for="years" class="form-label">No. of Years</label>
<input type="number" class="form-control" id="years" value="25">
</div>
<button type="button" class="btn btn-primary" onclick="compute()">Compute Interest</button>
<div class="mb-3 mt-4">
<label for="result" class="form-label">Result</label>
<p id="result"></p>
</div>
</form>
Try this
function getresult() {
var result = '';
result += 'If you deposit:P' +
'at an interest rate of R' +
'in the year Y' +
'You will receive an amount of R';
document.getElementById("result").innerHTML = result;
}

I am trying to conduct a while loop but the loop is infinite and I am unsure why

I was constructing this code and after testing it, the code does not work and it froze the webpage, which I assume is because of an infinite loop. I am unsure what the problem is.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student Loan Payoff</title>
<script type="text/javascript">
function DisplayPayoffSchedule() {
var amount, ir, mp, monthcounter;
amount = parseFloat(document.getElementById('loanBox').value);
ir = parseFloat(document.getElementById('rateBox').value);
mp = parseFloat(document.getElementById('paymentBox').value);
document.getElementById('scheduleDiv').innerHTML = 'Original loan amount: ' + amount + '<br>';
monthcounter = 0;
while (amount > mp) {
amount = (1 + (ir / 12)) * amount - mp;
monthcounter++;
document.getElementById('scheduleDiv').innerHTML += ' Month ' + monthcounter + ': Amount Remaining : ' + amount + '<br>';
}
}
</script>
</head>
<body>
<p>
Amount of Loan: <input type="text" id="loanBox" size="6"><br>
Annual Interest Rate: <input type="text" id="rateBox" size="6"><br>
Monthly Payment: <input type="text" id="paymentBox" size="6">
</p>
<input type="button" value="Display Payoff Schedule" onclick="DisplayPayoffSchedule();">
<hr>
<div id="scheduleDiv"></div>
</body>
</html>
The error because of
amount = (1 + (ir / 12)) * amount - mp;
If you enter Monthly Payment is negative, the amount alway greater than mp and endless loop.
Should prevent input negative number.
Also should break while when monthcounter is too big.
if(monthcounter > 50){
break;
}
Because if Amount of Loan is too big and Interest Rate and Monthly Payment is very small, it will repeat a lot of loops and seem as endless loop.
function DisplayPayoffSchedule() {
var amount, ir, mp, monthcounter;
amount = parseFloat(document.getElementById('loanBox').value);
ir = parseFloat(document.getElementById('rateBox').value);
mp = parseFloat(document.getElementById('paymentBox').value);
if(mp < 0){
alert('Monthly Payment must be positive');
return;
}
document.getElementById('scheduleDiv').innerHTML = 'Original loan amount: ' + amount + '<br>';
monthcounter = 0;
while (amount > mp) {
amount = (1 + (ir / 12)) * amount - mp;
monthcounter++;
document.getElementById('scheduleDiv').innerHTML += ' Month ' + monthcounter + ': Amount Remaining : ' + amount + '<br>';
if(monthcounter > 50){
break;
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student Loan Payoff</title>
<script type="text/javascript">
function DisplayPayoffSchedule() {
var amount, ir, mp, monthcounter;
amount = parseFloat(document.getElementById('loanBox').value);
ir = parseFloat(document.getElementById('rateBox').value);
mp = parseFloat(document.getElementById('paymentBox').value);
if(mp < 0){
alert('Monthly Payment must be positive');
return;
}
document.getElementById('scheduleDiv').innerHTML = 'Original loan amount: ' + amount + '<br>';
monthcounter = 0;
while (amount > mp) {
amount = (1 + (ir / 12)) * amount - mp;
monthcounter++;
document.getElementById('scheduleDiv').innerHTML += ' Month ' + monthcounter + ': Amount Remaining : ' + amount + '<br>';
if(monthcounter > 50){
break;
}
}
}
</script>
</head>
<body>
<p>
Amount of Loan: <input type="text" id="loanBox" size="6"><br>
Annual Interest Rate: <input type="text" id="rateBox" size="6"><br>
Monthly Payment: <input type="text" id="paymentBox" size="6">
</p>
<input type="button" value="Display Payoff Schedule" onclick="DisplayPayoffSchedule();" />
<hr>
<div id="scheduleDiv"></div>
</body>
</html>

Why does my Javascript code only calculate my age only on the first click of the submit button only?

I have a java-script code which calculates a person age.
A user will enter his/her identity number in an input field and clicks submit. then the java-script code will calculate their age.
i do not understand why the java-script code does not calculate a different age when i change the identity number.
eg identity number 1: 7810104455082, identity number 2: 8001013355088 and identity number 3: 9502242235086
my html code below:
<input id="IDNumber" type="text" name="idnumber" placeholder="ID number" />
<input onclick="return validateID();" id="submit" type="submit" value="Submit" />
<p id="demo">demo</p> <p id="demo2">demo2</p>
<div id="screen" style="width:600px; height:400px; background-color:gray;"></div>
<button id="display">Display</button>
my javascript code below:
<script>
function validateID() {
var ex = /^(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))/;
var idNumber = document.getElementById("IDNumber").value;
if (ex.test(idNumber) == false) {
// alert code goes here
document.getElementById("demo").innerHTML = "Please supply a valid ID number" ;
alert('Please supply a valid ID number');
return false;
}
//Pull out Year and Month and Day for IDNumber
var tempDate = new Date(idNumber.substring(0, 2), idNumber.substring(2, 4) - 1, idNumber.substring(4, 6));
var id_date = tempDate.getDate();
var id_month = tempDate.getMonth();
var id_year = tempDate.getFullYear();
// set variable of fullDate to insert in math calculation
var fullDate = id_year + "/" + (id_month + 1) + "/" + id_date;
//math time calculation to give mil and convert to years
var d1 = new Date(); //"now"
var d2 = new Date(fullDate) // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var yeardiff = diff / 31536000000;
document.getElementById("demo").innerHTML = "The Age is " + Math.round(yeardiff);
}
</script>
Remove the return on your onclick
<input onclick="validateID();" id="submit" type="submit" value="Submit" />

Form submit not showing JavaScript output

Trying to have it so that when the user hit's submit it will show their info inputted and calculated volume/cost that's done in javascript. However the submit button isn't showing anything when clicked. Sorry for my poor english and if it's not clear. Let me know if you need anything clarified. Here's the related code:
HTML:
<form name="landscape" action="index.html" onsubmit="return validateForm()" method="post">
...
...
<h3>Type of Planter:</h3>
<input type="radio" name="inputcontrol" value="10" id="inputcontrol1" onchange="setvisible(this.value)">Square/Rectangular Cubes
<input type="radio" name="inputcontrol" value="12" id="inputcontrol2" onchange="setvisible(this.value)">Flat bottmed cylinders
<br>
<input type="radio" name="inputcontrol" value="15" id="inputcontrol3" onchange="setvisible(this.value)">1/2 Spherical
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
<br>
<br>
Length:<p><input type="text" size="10" id="set1" style="visibility:hidden;" ></p>
Width:<p><input type="text" size="10" id="set2"style="visibility:hidden;" ></p>
Height:<p><input type="text" size="10" id="set3"style="visibility:hidden;" ></p>
Radius:<p><input type="text" size="10" id="set4"style="visibility:hidden;" ></p>
Radius2:<p><input type="text" size="10" id="set5"style="visibility:hidden;" ></p>
<input type=submit value="Submit" onClick="buttonandchecks();">
</form>
<br>
<br>
<h2>Order Form: </h2><h2><span id="result"></span></h2>
</body>
</html>
JAVASCRIPT:
function buttonandchecks()
{
var x;
var radio_value;
var planter="";
var infooutput="";
var total=parseFloat(0);
var volume=parseFloat(0);
var length = document.getElementById("set1").value;
var width = document.getElementById("set2").value;
var height = document.getElementById("set3").value;
var radius = document.getElementById("set4").value;
var radius2 = document.getElementById("set5").value;
var inputcontrol1 = document.getElementById("inputcontrol1");
var inputcontrol2 = document.getElementById("inputcontrol2");
var inputcontrol3 = document.getElementById("inputcontrol3");
var inputcontrol4 = document.getElementById("inputcontrol4");
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
radio_value=parseFloat(radio_value);
if(inputcontrol1.checked)
{
volume = length * width * height;
planter = "Square/Rectangular Cubes";
}
if(inputcontrol2.checked)
{
volume = 3.14 * radius * radius * height;
planter = "Flat bottomed cylinders";
}
if(inputcontrol3.checked)
{
volume = 1/2 * (4/3* 3.14 * radius * radius * radius);
planter = "1/2 Spherical";
}
if(inputcontrol4.checked)
{
volume = 1/3*3.14*(radius*radius*radius*radius2*radius2*radius2)*height;
planter = "Truncated cone";
}
total=radio_value * volume;
infooutput=("Firstname: " + (Text1).value + " Lastname: " + (Lname).value + " \nAddress: " + (Add).value + " \nPostal Code: " + (StPrv).value + "\n\n Planter: " + planter + "\nLength: " + length + " Width: " + width + " Height: " + height + " radius: " + radius + " 2nd radius: " + radius2 + "\n Volume: " + volume + "\n Total: " + total);
document.getElementById("result").innerHTML=infooutput;
}
Any help would be greatly appreciated. Sorry if my code isn't that good, I just started learning a week ago. Thank you!
Theres a few things that need updating.
HTML
Your last input is not structured correctly.
type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)">Truncated Cone
Instead, try:
<label><input type="radio" name="inputcontrol" id="inputcontrol4" value="20" onchange="setvisible(this.value)" />Truncated Cone</label>
JavaScript
Things like document.landscape.inputcontrol[x].checked and (Text1).value are not valid ways to access DOM elements. Instead, try document.getElementById() or document.getElementsByName()
For example, change
for(x=0;x<document.landscape.inputcontrol.length;x++)
{
if(document.landscape.inputcontrol[x].checked)
{
radio_value=document.lanscape.inputcontrol[x].value;
}
}
To this: (notice the bracket positions and indents for readability)
checkboxes = document.getElementsByName('inputcontrol');
for(x=0;x<checkboxes.length;x++) {
if(checkboxes[x].checked) {
radio_value=checkboxes[x].value;
}
}
Finally, if your validateForm() function is going to return true, then your form will post to index.html and the page will load losing anything that happened in buttonandchecks(). Instead, you may need to have that method return false, or remove the form tag.
For some examples of those changes, you can see it working in this JS Fiddle: https://jsfiddle.net/igor_9000/qfz6dr25/2/
Hope that helps!

Increment Serial Numbers and calculate - javascript

Our company has a client that requires a specific checksum on their bar codes. I've come up with the following which allows the user to enter the distributor part number, our part number and our serial number. Right now, when you click save, it will calculate correctly for the bar code with the checksum. NOW, we have added a quantity box so that we can print x number of barcodes with our serial number incrementing by 1. (i.e. 1st serial number is 000001, next will be 000002 and so on). What I've been trying to do for the last week is alter this code so the user can input the part numbers and sn, and it will calculate each bar code up to the quantity.
This is what we would like to have:
If user enters part numbers, first serial number and quantity then clicks "Save" this should be the result. At present, this can only be achieved by entering each serial number and clicking save
*note: while the quantity can be entered, the actual value has not been used in my code...yet
So, to achieve this, I need to find a way to increment the serial numbers without dropping off the leading zeros but maintaining the length of qty.length.
I also need to figure out how to loop each new serial number through with part numbers to get the correct checksum for the bar code. After a week of staring at this, I'm hoping some fresh and experienced eyes can assist. Here is my code.
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Capture Form Fields to CSV</title>
<script type="text/javascript">
<!--
function saveValues() {
var frm = document.form1;
var str = frm.text1.value + frm.text2.value + frm.text3.value;
var dpn = frm.text1.value;
var wpn = frm.text2.value;
var wsn = frm.text3.value;
var strArray = str.split("");
var calcArray = strArray;
var total =0;
for (var i = 0; i < str.length; i++)
strArray[i] = strArray[i].charCodeAt(0);
for (var i = 0; i < strArray.length; i++){
if (strArray[i] >= 65 && strArray[i] <= 90){
calcArray[i] = (strArray[i] - 64) * (i+1)
}
else if (strArray[i] >=97 && strArray[i] <=122) {
calcArray[i] = (strArray[i] - 96) * (i+1)
}
else if (strArray[i] >=48 && strArray[i] <=57) {
calcArray[i] = (strArray[i] - 48) * (i+1)
}
else {
calcArray[i] = 1 * (i+1)
}
}
for (var i in calcArray){
total += calcArray[i];}
var mod2 = str.length - (2*(Math.floor(str.length/2)));
var mod10 = (total + mod2) - (10*(Math.floor((total + mod2)/10))) ;
var chk = mod10;
var record = ""
+ dpn + "," + wpn + "," + wsn + "," +dpn + "~" + wpn + "~" + wsn + "~" + chk + "\n";
frm.textarea1.value += record;
}
function clearText() {
document.form1.textarea1.value = "";P
form1.text1.value = "";
form1.text2.value = "";
form1.text3.value = "";
}
function csvSave() {
var a = document.createElement('a');
with (a) {
href='data:text/csv;base64,' + btoa(document.getElementById('textarea1').value);
download='csvfile.csv';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//-->
</script>
</head>
<body>
<h1>Capture Form Fields to CSV</h1>
<form name="form1" >
<p>
Distributor Part Number: <input name="text1" type="text" value="GDM1301" /><br />
Our Part Number: <input name="text2" type="text" value="PCBDM160"/><br />
Our Serial Number: <input name="text3" type="text" value="000001"/><br />
Label Quantity: <input name="qty" type="text" value="3"/>
</p>
<p>
<input name="save" type="button" value="Save"
onclick="saveValues(); return false"/>
 
<input name="clear" type="button" value="Clear"
onclick="clearText(); return false"/>
<button onclick="csvSave()">CSV</button>
</p>
<p>
<i>Click 'Save' to add content</i><br />
<textarea id="textarea1" cols="80" rows="20"></textarea>
</p>
</form>
</body>
</html>

Categories

Resources