I am currently learning javascript. I have created a calculator to find invesment future value. It is giving me an incorrect value when it displays the future value
. I have checked the formula several times but it still gives me an error. Also, I have set alerts to appear if the interest is less than 0
or greater than 20
but nothing is showing. How would i be able to properly display the correct future value and alerts when necessary? Example
Javascript
var $ = function (id) { return document.getElementById(id); } var calculate_click = function () { var investment = parseFloat( $("investment").value ); var annualRate = parseFloat( $("rate").value ) /100; var years = parseInt( $("years").value ); $("futureValue").value = ""; if (isNaN(investment) || investment <= 0) { alert("Investment must be a valid numbernand greater than zero."); } else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) { alert("Annual rate must be a valid numbernand less than or equal to 20."); } else if(isNaN(years) || years <= 0 || years > 50) { alert("Years must be a valid numbernand less than or equal to 50."); } else { //var monthlyRate = annualRate / 12; //var months = years * 12; var futureValue = 0; for ( i = 1; i <= years; i++ ) { futureValue = ( futureValue + investment ) * ( 1 + annualRate ); } $("futureValue").value = futureValue.toFixed(2); } } var clear_click = function () { $("investment").value = ""; $("rate").value = ""; $("years").value = ""; $("futureValue").value = ""; } window.onload = function () { $("calculate").onclick = calculate_click; $("investment").focus(); $("clear").onclick = clear_click; }
Advertisement
Answer
Using .value
is incorrect, its javascript, while this is jquery, try adding a #
in front and use .val()
instead.
Its similar to this:
jquery function val() is not equivalent to “$(this).value=”?
EDIT
He’s not using jquery, ignore this.