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
JavaScript
x
45
45
1
var $ = function (id) {
2
return document.getElementById(id);
3
}
4
5
var calculate_click = function () {
6
var investment = parseFloat( $("investment").value );
7
var annualRate = parseFloat( $("rate").value ) /100;
8
var years = parseInt( $("years").value );
9
10
$("futureValue").value = "";
11
12
if (isNaN(investment) || investment <= 0) {
13
alert("Investment must be a valid numbernand greater than zero.");
14
} else if(isNaN(annualRate) || annualRate <= 0 || annualRate > 20) {
15
alert("Annual rate must be a valid numbernand less than or equal to 20.");
16
} else if(isNaN(years) || years <= 0 || years > 50) {
17
alert("Years must be a valid numbernand less than or equal to 50.");
18
} else {
19
//var monthlyRate = annualRate / 12;
20
//var months = years * 12;
21
var futureValue = 0;
22
23
for ( i = 1; i <= years; i++ ) {
24
25
futureValue = ( futureValue + investment ) *
26
( 1 + annualRate );
27
28
}
29
$("futureValue").value = futureValue.toFixed(2);
30
}
31
}
32
33
var clear_click = function () {
34
$("investment").value = "";
35
$("rate").value = "";
36
$("years").value = "";
37
$("futureValue").value = "";
38
}
39
40
window.onload = function () {
41
$("calculate").onclick = calculate_click;
42
$("investment").focus();
43
$("clear").onclick = clear_click;
44
}
45
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.