Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 10-12-2012, 12:03 AM   PM User | #1
logepoge1
New Coder

 
Join Date: Oct 2012
Posts: 44
Thanks: 3
Thanked 0 Times in 0 Posts
logepoge1 is an unknown quantity at this point
Exclamation Help me with this code

I am coding this website using html5, css3, and javascript for class. We are supposed to make it where you can enter the Principle, Interest Rate, and term of a loan and get the monthly payment as the answer. I have everything entered, but cannot get the alert box to pop up with the answer. I believe that as soon as it pops up, it clears but I may not be write.

Here is the HTML file:
Code:
<!DOCTYPE html>
<html lang="en-us">

	<head>
		<meta charset="utf-8">
		<title>Loan Payments</title>
		<!-- <link rel="stylesheet" href="form.css" /> -->
		<script type="text/Javascript" src="interest.js">
		</script>
	</head>
	
	<body>
		<h1>Loan Payments Calculator</h1>
		
		<form name="interest_form" id="myform" method="get" onsubmit="calculate_payments();">
			<p>
				<label for="P"> Enter the Purchase Price: </label>
				<input type="text" id="P" name="P" />
			</p>
			
			<p>
				<label for="D">Enter the Downpayment: </label>
				<input type="text" id="D" name="D" />
			</p>
			
			<p>
				<label for="Interest">Enter Interest Rate: </label>
				<input type="text" id="I" name="I" />
			</p>
			
			<p>
				<label for="Number"> Enter Number of Payments: </label>
				<input type="text" id="N" name="N" />
			</p>
			
			<p>
				<input type="submit" value="Calculate" />
				<input type="reset" Value="Clear" />
			</p>
		</form>
		
		<p><span id="calculated_payments"></span></p>
		
	</body>
</html>
And here is the javascript:
Code:
function calculate_payments()
{ 

	var M = document.forms["interest_form"]["M"].value;
	if (isNonNumeric(M))
	{
		document.getElementById('werror').innerHTML="Value must be numeric.";
		document.forms['interest_form']['M'].focus;
		
	}
	var I = document.forms['interest_form']['I'].value;
	if (isNonNumeric(I))
	{
		document.getElementById('werror').innerHTML="Value must be numeric.";
		document.forms['interest_form']['I'].focus;
		
	}
	var N = document.forms["interest_form"]["N"].value;
	if (isNonNumeric(N))
	{
		document.getElementById('werror').innerHTML="Value must be numeric.";
		document.forms['interest_form']['N'].focus;
		
	}
	var P = document.forms["interest_form"]["P"].value;
	if (isNonNumeric(P))
	{
		document.getElementById('werror').innerHTML="Value must be numeric.";
		document.forms['interest_form']['P'].focus;
	}
	
	var J = I / 12;
	var Z = P - D;
	var M = Z * ((J+1)^N) * J / ((Math.pow(J+1,N)) - 1);
	
	var str;
	str = "The monthly payment is " + M;
	document.write(str);
	alert();
	alert(str);
}

function isNonNumeric(myString)
{
	valid_characters = "0123456789";
	
	for (var i = 0; i < myString.length; i++)
	{
		char = myString.charAt(i);
		if(valid_characters.indexOf(char) == -1) return true;
	}
	
	return false;

}
I havent gotten to the CSS yet because that is obviously the easiest part so I am saving it for later. Thanks and please reply. And I just need help figuring out why the alert wont pop up right. I will do the error messages later.

Last edited by logepoge1; 10-12-2012 at 03:08 AM.. Reason: Changed to resolved
logepoge1 is offline   Reply With Quote
Old 10-12-2012, 12:21 AM   PM User | #2
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
This line is the culprit:
Code:
    document.write(str);
If you use document.write AFTER the page is fully loaded (that is, after the browser has processed the </html> tag) then it will *WIPE OUT* ALL CONTENT on that page. Yes, INCLUDING even the JavaScript that did the document.write!

KILL THAT LINE.

There are other errors there. Just for example, if the user enters 6.5 for the interest rate, you will not allow it. HINT: Your isNonNumeric code is wrong and in any case is not needed. Learn to use JavaScripts isNaN( ) built-in function.

More things wrong, but I'll let you discover them.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 10-12-2012, 12:26 AM   PM User | #3
logepoge1
New Coder

 
Join Date: Oct 2012
Posts: 44
Thanks: 3
Thanked 0 Times in 0 Posts
logepoge1 is an unknown quantity at this point
Quote:
Originally Posted by Old Pedant View Post
This line is the culprit:
Code:
    document.write(str);
If you use document.write AFTER the page is fully loaded (that is, after the browser has processed the </html> tag) then it will *WIPE OUT* ALL CONTENT on that page. Yes, INCLUDING even the JavaScript that did the document.write!

KILL THAT LINE.

There are other errors there. Just for example, if the user enters 6.5 for the interest rate, you will not allow it. HINT: Your isNonNumeric code is wrong and in any case is not needed. Learn to use JavaScripts isNaN( ) built-in function.

More things wrong, but I'll let you discover them.
Okay new code(Note that getting rid of document.write didnt fix anything.)
Code:
function calculate_payments()
{ 

	var M = document.forms["interest_form"]["M"].value;
	
	var I = document.forms['interest_form']['I'].value;
	
	var N = document.forms["interest_form"]["N"].value;
	
	var P = document.forms["interest_form"]["P"].value;
	
	
	
	var J = I / 12;
	var Z = P - D;
	var M = Z * ((J+1)^N) * J / ((Math.pow(J+1,N)) - 1);
	
	var str;
	str = "The monthly payment is " + M;
	alert();
	alert(str);
}
I originally had just alert("The monthly payment is " + M") but that didnt work so someone I went to added the other stuff. Note: If I go to the html and change it from onsubmit="calculate_payments() to onsubmit="alert() it pops up a message that says undefined. Thanks
logepoge1 is offline   Reply With Quote
Old 10-12-2012, 12:44 AM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
You are doing this:
Code:
	var M = document.forms["interest_form"]["M"].value;
but there is no form field named "M". KABLOOEY!

THen you do this:
Code:
var Z = P - D;
but D isn't defined. KABLOOEY!
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 10-12-2012, 12:50 AM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Oh...and you are using ^ apparently to mean "power of" and it doesn't mean anything close to that in JavaScript.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 10-12-2012, 12:55 AM   PM User | #6
logepoge1
New Coder

 
Join Date: Oct 2012
Posts: 44
Thanks: 3
Thanked 0 Times in 0 Posts
logepoge1 is an unknown quantity at this point
Quote:
Originally Posted by Old Pedant View Post
You are doing this:
Code:
	var M = document.forms["interest_form"]["M"].value;
but there is no form field named "M". KABLOOEY!

THen you do this:
Code:
var Z = P - D;
but D isn't defined. KABLOOEY!
Now I am getting one alert that says undefined and after I close it I get: the monthly payment is NaN. And give a beginner coder a chance.Of course here is the new code:

Code:
function calculate_payments()
{ 

	var M = document.forms["interest_form"]["M"].value;
	
	var I = document.forms['interest_form']['I'].value;
	
	var N = document.forms["interest_form"]["N"].value;
	
	var P = document.forms["interest_form"]["P"].value;
	
	var D = document.forms["interest_form"]["D"].value;
	
	var J = (I * 100) / 12;
	var Z = P - D;
	var M = Z * ((Math.pow(J+1)^N)) * J / ((Math.pow(J+1,N)) - 1);
	
	var str;
	str = "The monthly payment is " + M;
	alert();
	alert(str);
}
logepoge1 is offline   Reply With Quote
Old 10-12-2012, 01:10 AM   PM User | #7
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
As I said, you are misusing the * operator.

On top of that, though, you have the formula all wrong.

And, finally, you don't want to do thie onsubmit of the <form>, because as soon as the alert finishes, the form submits back to the server and, essentially, you start all over.

You should *NOT* be using a submit button for this. Use an ordinary button and then attach the calculate function to it.

Here is a complete working page. And with REASONABLE variable names. Don't use one-letter names that don't convey their meaning. I would also change the form field names, were I you.
Code:
<!DOCTYPE html>
<html lang="en-us">

	<head>
		<meta charset="utf-8">
		<title>Loan Payments</title>
		<script type="text/Javascript">
function calculate_payments(btn)
{ 

	var form = btn.form;
        var price = Number(form.P.value);
        var down  = Number(form.D.value);
        var annualrate = Number(form.I.value);
        var count = Number(form.N.value);

        if ( isNaN(price) || isNaN(down) || isNaN(annualrate) || isNaN(count) )
        {
            alert("All values entered must be numbers.");
            return;
        }

        var loanAmount = price - down;
        var irate = annualrate / 1200; // convert % to decimal and account for 12 months        

	var monthly = loanAmount / ( ( 1 - Math.pow( 1 + irate, - count ) ) / irate );
        document.getElementById("calculated_payments").innerHTML = monthly.toFixed(2);

}

		</script>
	</head>
	
	<body>
		<h1>Loan Payments Calculator</h1>
		
		<form method="get">
			<p>
				<label for="P"> Enter the Purchase Price: </label>
				<input type="text" id="P" name="P" />
			</p>
			
			<p>
				<label for="D">Enter the Downpayment: </label>
				<input type="text" id="D" name="D" />
			</p>
			
			<p>
				<label for="Interest">Enter Interest Rate: </label>
				<input type="text" id="I" name="I" />
			</p>
			
			<p>
				<label for="Number"> Enter Number of Payments: </label>
				<input type="text" id="N" name="N" />
			</p>
			
			<p>
				<input type="button" value="Calculate" onclick="calculate_payments(this);" />
				<input type="reset" Value="Clear" />
			</p>
		</form>
		
		<p><span id="calculated_payments"></span></p>
		
	</body>
</html>
You can move the JS code into a separate file if you wish.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 10-12-2012, 01:15 AM   PM User | #8
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
And here is the *MODERN* way to do this:
Code:
<!DOCTYPE html>
<html lang="en-us">

	<head>
		<meta charset="utf-8">
		<title>Loan Payments</title>
	</head>
	
	<body>
		<h1>Loan Payments Calculator</h1>
		
		<form id="myForm" method="get">
			<p>
				<label for="P"> Enter the Purchase Price: </label>
				<input type="text" id="P" name="P" />
			</p>
			
			<p>
				<label for="D">Enter the Downpayment: </label>
				<input type="text" id="D" name="D" />
			</p>
			
			<p>
				<label for="Interest">Enter Interest Rate: </label>
				<input type="text" id="I" name="I" /> (Annual rate, as a percentage)
			</p>
			
			<p>
				<label for="Number"> Enter Number of Payments: </label>
				<input type="text" id="N" name="N" /> (Should be number of months)
			</p>
			
			<p>
				<input type="button" name="calc" value="Calculate" />
				<input type="reset" Value="Clear" />
			</p>
		</form>
		
		<p>Monthly payment will be: <span id="calculated_payments"></span></p>
		
<script type="text/Javascript">
(
  function( )
  {
      var form = document.getElementById("myForm");

      form.calc.onclick = function( )
      {
          var price = Number(form.P.value);
          var down  = Number(form.D.value);
          var annualrate = Number(form.I.value);
          var count = Number(form.N.value);

          if ( isNaN(price) || isNaN(down) || isNaN(annualrate) || isNaN(count) )
          {
              alert("All values entered must be numbers.");
              return;
          }

          var loanAmount = price - down;
          var irate = annualrate / 1200; // convert % to decimal and account for 12 months        

          var monthly = loanAmount / ( ( 1 - Math.pow( 1 + irate, - count ) ) / irate );
          document.getElementById("calculated_payments").innerHTML = monthly.toFixed(2);

      }
  }
)( );
</script>


	</body>
</html>
The script goes AFTER the HTML and there is no JavaScript embedded in the HTML.

Further, the script introduces ZERO global variables to the page, so it can't possibly interfere with any other scripts on the page.

The technique is what I call a "self-invoking anonymous function."
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.

Last edited by Old Pedant; 10-12-2012 at 01:18 AM..
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
logepoge1 (10-12-2012)
Old 10-12-2012, 01:16 AM   PM User | #9
logepoge1
New Coder

 
Join Date: Oct 2012
Posts: 44
Thanks: 3
Thanked 0 Times in 0 Posts
logepoge1 is an unknown quantity at this point
Smile

Quote:
Originally Posted by Old Pedant View Post
As I said, you are misusing the * operator.

On top of that, though, you have the formula all wrong.

And, finally, you don't want to do thie onsubmit of the <form>, because as soon as the alert finishes, the form submits back to the server and, essentially, you start all over.

You should *NOT* be using a submit button for this. Use an ordinary button and then attach the calculate function to it.

Here is a complete working page. And with REASONABLE variable names. Don't use one-letter names that don't convey their meaning. I would also change the form field names, were I you.
Code:
<!DOCTYPE html>
<html lang="en-us">

	<head>
		<meta charset="utf-8">
		<title>Loan Payments</title>
		<script type="text/Javascript">
function calculate_payments(btn)
{ 

	var form = btn.form;
        var price = Number(form.P.value);
        var down  = Number(form.D.value);
        var annualrate = Number(form.I.value);
        var count = Number(form.N.value);

        if ( isNaN(price) || isNaN(down) || isNaN(annualrate) || isNaN(count) )
        {
            alert("All values entered must be numbers.");
            return;
        }

        var loanAmount = price - down;
        var irate = annualrate / 1200; // convert % to decimal and account for 12 months        

	var monthly = loanAmount / ( ( 1 - Math.pow( 1 + irate, - count ) ) / irate );
        document.getElementById("calculated_payments").innerHTML = monthly.toFixed(2);

}

		</script>
	</head>
	
	<body>
		<h1>Loan Payments Calculator</h1>
		
		<form method="get">
			<p>
				<label for="P"> Enter the Purchase Price: </label>
				<input type="text" id="P" name="P" />
			</p>
			
			<p>
				<label for="D">Enter the Downpayment: </label>
				<input type="text" id="D" name="D" />
			</p>
			
			<p>
				<label for="Interest">Enter Interest Rate: </label>
				<input type="text" id="I" name="I" />
			</p>
			
			<p>
				<label for="Number"> Enter Number of Payments: </label>
				<input type="text" id="N" name="N" />
			</p>
			
			<p>
				<input type="button" value="Calculate" onclick="calculate_payments(this);" />
				<input type="reset" Value="Clear" />
			</p>
		</form>
		
		<p><span id="calculated_payments"></span></p>
		
	</body>
</html>
You can move the JS code into a separate file if you wish.
Oh wow. Thanks it works. Now I will go off and make it look better with some CSS3 and HTML5. Thanks for the help. I will mark the thread as solved in about 1 hour and I will make sure to click to thank you.
logepoge1 is offline   Reply With Quote
Old 10-12-2012, 01:25 AM   PM User | #10
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Just for fun:
http://www.juncojunction.com/juncoju...alculator.html

I created that page as part of a contest in 1998 (maybe 1997?) where the challenge was to create a self-contained USEFUL HTML page in 5K bytes of code. (5K being 5120 bytes)

I actually got the basic calculations down just under 3K, but then I added the ability to pop up a window that shows either the monthly or annual amortization AND allows you to specify that you want UN-rounded numbers.

The code is, of course, really ancient. It was before (for example) the Number.toFixed() method was available, so I did my own rounding. It really is amazing what you can shove into 5K bytes if you have to.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 10-12-2012, 01:28 AM   PM User | #11
logepoge1
New Coder

 
Join Date: Oct 2012
Posts: 44
Thanks: 3
Thanked 0 Times in 0 Posts
logepoge1 is an unknown quantity at this point
Quote:
Originally Posted by Old Pedant View Post
Just for fun:
http://www.juncojunction.com/juncoju...alculator.html

I created that page as part of a contest in 1998 (maybe 1997?) where the challenge was to create a self-contained USEFUL HTML page in 5K bytes of code. (5K being 5120 bytes)

I actually got the basic calculations down just under 3K, but then I added the ability to pop up a window that shows either the monthly or annual amortization AND allows you to specify that you want UN-rounded numbers.

The code is, of course, really ancient. It was before (for example) the Number.toFixed() method was available, so I did my own rounding. It really is amazing what you can shove into 5K bytes if you have to.
Nice. I am in a basic web design class right now so this is the first time I have really understood javascript. I will be taking C++ and Java later on it college when I work on a degree in computer/electrical engineering
logepoge1 is offline   Reply With Quote
Reply

Bookmarks

Tags
javascript, javascript help

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 12:29 PM.


Advertisement
Log in to turn off these ads.