Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New Coder
    Join Date
    Oct 2012
    Posts
    44
    Thanks
    3
    Thanked 0 Times in 0 Posts

    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 04:08 AM. Reason: Changed to resolved

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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.

  • #3
    New Coder
    Join Date
    Oct 2012
    Posts
    44
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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.

  • #6
    New Coder
    Join Date
    Oct 2012
    Posts
    44
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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);
    }

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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."
    Last edited by Old Pedant; 10-12-2012 at 02:18 AM.
    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.

  • Users who have thanked Old Pedant for this post:

    logepoge1 (10-12-2012)

  • #9
    New Coder
    Join Date
    Oct 2012
    Posts
    44
    Thanks
    3
    Thanked 0 Times in 0 Posts

    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.

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,202
    Thanks
    80
    Thanked 4,563 Times in 4,527 Posts
    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.

  • #11
    New Coder
    Join Date
    Oct 2012
    Posts
    44
    Thanks
    3
    Thanked 0 Times in 0 Posts
    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


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •