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;
}
Related
Good Morning,
Does anyone know how to correct the code below? First, I prompt the user for the variables first and second but am failing to have them display on the form. Second, when the user clicks on the Determine the larger number button it is supposed to run the if and else if statement located under the function determineLarge(){ but it fails to run. My apologies as I am learning at the university to code this language. Thank you for the help.
<script>
function determineLarge(){
let first = prompt ("Enter the first number.");
first= document.myForm.first.value;
let second = prompt("Enter the second number.");
second =document.myForm.first.value;
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first <0 || second <0){
message = "You can't use negative numbers.";
}
else if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:determineLarge();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:determineLarge();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>
I separated the getting of the values and processing of them into two functions.
I put the prompts in a while loop so you are forced to enter in a real value greater than zero.
Also you overwrite the first and second variables by keeping the variable name first ie: first = .... instead of document.myform.value == first etc..
first = -1;
second = -1;
function getValues(){
while(isNaN(first) || first == "" || first < 0){
first = prompt ("Enter the first number.");
}
while(isNaN(second) || second == "" || second < 0){
second = prompt ("Enter the second number.");
}
document.myForm.first.value = first;
document.myForm.second.value = second;
}
function determineLarge(){
let message = "";
if (first > second){
message = "The second number" + "(" + second + ")" + " is smaller.";
}
else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
else if (first == second || second==first){
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="" onclick="javascript:getValues();">
<p>Enter the second number</p>
<input type="number" name="second" value="" onclick="javascript:getValues();">
<button type="button" onclick="determineLarge();">Determine the larger number</button>
</form>
<div id="results"> </div>
I removed the prompt so that the inputs can be used. No need to call onClick on the text input.
<script>
function determineLarge(myForm) {
var first = myForm.first.value;
var second = myForm.second.value;
console.log(first, second)
first = parseFloat(first);
second = parseFloat(second);
let message = "";
if (first < 0 || second < 0) {
message = "You can't use negative numbers.";
} else if (first > second) {
message = "The second number" + "(" + second + ")" + " is smaller.";
} else if (second > first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
} else if (first == second || second == first) {
message = "The first number" + "(" + first + ")" + " is smaller.";
}
document.getElementById("results").innerHTML = message;
}
</script>
</head>
<body>
<h1>Gary's Smaller of Two Numbers</h1>
<form name="myForm">
<p> Enter the first number</p>
<input type="number" name="first" value="">
<p>Enter the second number</p>
<input type="number" name="second" value="">
<button type="button" onclick="determineLarge(this.form);">Determine the larger number</button>
</form>
<div id="results"> </div>
</body>
Prints '2 x 10 = 20' but not the whole table when the input is 2. I tried various means. But the result is same.
No error. Just like to print the whole multiplication table.
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
document.getElementById("result").value = x + " x " + i + " = " + i * x;
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
You are always changing the value of 'result' rather than adding to it:
function loop() {
var i = 1;
var x = document.getElementById("num").value;
//document.getElementById("result").value = result;
while (i <= 10) {
var result = document.getElementById("result");
var sum = document.createTextNode(x + " x " + i + " = " + i * x + "\n");
result.appendChild(sum);
i++;
}
}
<h1>While loop: </h1>
<p>The while loop keeps repeating an action until an associated condition returns false.</p>
<img src="images/loop.jpg" /><br/>
<img src="images/loop2.jpg" /><br/>
<body>
<p>JavaScripts Runs:</p>
<script src="while_1loop.js">
</script><br/> What number table would you like to have?<input type="number" name="" id="num" /><br>
<button type="button" onclick="loop()" ;>Start</button><br>
<textarea rows="12" cols="15" id="result" readonly>
</textarea><br/>
If I understand what you mean,
You rewrite whole textarea with this code:
document.getElementById("result").value = x + " x " + i + " = " + i * x;
but you need add new result after older results. Something like this:
var oldValue = document.getElementById("result").value;
var result = x + " x " + i + " = " + i * x;
document.getElementById("result").value = oldValue + '\n' + result;
When the user clicks the button to show all values in the array, how can I get it to add up the total of all 'amounts due'? For example, if one user enters $5, another enters $10 and another enters $25, the total would be displayed as $40.
// Code goes here
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
</body>
</html>
I have changed your code as per your requirement as shown below.Hopefully it will solve your problem
// Code goes here
var customerarray = [];
function displaydata() {
var total=0;
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue+"<br/>";
total+=parseInt(customerarray[i].AmountDue);
}
document.getElementById('output').innerHTML ="User Input Data <br/>" +innerTemphtml;
document.getElementById('total').innerHTML = "Grand Total = "+total;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="text" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<p id="output"></p>
<p id="total"></p>
</body>
</html>
There are mutliple things you have to look. I have added a display due() for you.
And here is my js fiddle https://jsfiddle.net/jinspeter/1qxo50uz/
You have to user a number field for Amount. And also addding the amount has to parsed to Int to reject string.
<body>
<span>Customer Name: </span>
<input type="text" id='custName'/><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID'/><br><br>
<span>Amount: </span>
<input type="number" id='Amount'/> <br><br>
<button onClick="addtoarray();" class="button" type = "button">add to array</button>
<button onClick="displaydata()" class="button" type = "button"> Display data</button>
<button onClick="displayTotalDue()" class="button" type = "button"> Display Due</button>
<p id="output"></p>
</body>
var customerarray = [];
function displaydata() {
var innerTemphtml = ' ';
for (var i = 0; i < customerarray.length; i++) {
innerTemphtml += customerarray[i].customerName + " " + customerarray[i].customerID + " " + customerarray[i].AmountDue;
}
document.getElementById('output').innerHTML = innerTemphtml;
}
function displayTotalDue(){
var total =0;
customerarray.forEach(function(item){
total = total + item.AmountDue
});
var innerTemphtml = 'totalDue=' + total;
document.getElementById('output').innerHTML = innerTemphtml;
}
function addtoarray() {
customerarray.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: parseInt(document.getElementById('Amount').value)
});
console.log(customerarray);
}
I try to fix your code. To make it more easy to read. I put the displaydata() method inside of the addtoarray() method, so you can see the results after adding an element in the customers array. Also, I replaced the for with a forEach and added a new div for the total.
I create a node that is a p tag, which will contain the name, id and amount. This tag then will be added to the outputLabel for each element in the array. You can optimize this by just adding the additional node and not running the entire array to print the output.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata() {
outputLabel.innerHTML = '<p>Customers</p>';;
total = 0;
customers.forEach(function(customer) {
var node = document.createElement('p');
node.innerHTML = customer.customerName + ', ' +
customer.customerID + ', ' +
customer.AmountDue;
total += parseInt(customer.AmountDue);
outputLabel.appendChild(node);
});
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
customers.push({
customerName: document.getElementById('custName').value,
customerID: document.getElementById('CustID').value,
AmountDue: document.getElementById('Amount').value
});
displaydata();
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Optimized version: for this version I moved the node (p tag) to the addtoarray() method and I capture the data from the inputs. Then I calculate the total. With this two values a call the displaydata(). This method save time running the array each time you want to print the added element.
// Code goes here
var customers = [];
var outputLabel = document.getElementById('output');
var totalLabel = document.getElementById('total');
var total = 0;
outputLabel.innerHTML = '<p>Customers</p>';
totalLabel.innerHTML = 'Total: 0';
function displaydata(node, total) {
outputLabel.appendChild(node);
totalLabel.innerHTML = 'Total: ' + total;
}
function addtoarray() {
var customerName = document.getElementById('custName').value;
var customerID = document.getElementById('CustID').value;
var amountDue = document.getElementById('Amount').value;
customers.push({
customerName: customerName,
customerID: customerID,
amountDue: amountDue
});
var node = document.createElement('p');
node.innerHTML = customerName + ', ' + customerID + ', ' + amountDue;
total += parseInt(amountDue);
displaydata(node, total);
}
<span>Customer Name: </span>
<input type="text" id='custName' /><br><br>
<span>Customer ID: </span>
<input type="text" id='CustID' /><br><br>
<span>Amount: </span>
<input type="text" id='Amount' /> <br><br>
<button onClick="addtoarray();" class="button" type="button">Add to array</button>
<div id="output"></div>
<div id="total"></div>
Set "AmountDue" property of object to number instead of string at .push() call
Number(document.getElementById('Amount').value)
use Array.prototype.reduce() to add two elements of array at a time, return sum
let dues = customerarray.reduce((a, {AmountDue:b}) => a + b, 0);
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!
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")