0

I am working on making a simple interest calculator but I keep getting Not a Number:

<script type="text/javascript">
function intcal() {
var pr=document.getElementById("P");
var ra=document.getElementById("r");
var ti=document.getElementById("t");
var interest=pr*ra*ti;
document.write(interest);
}
</script>
<h1> Principal </h1>
<Input type="number" id="P" name="Principal" Size="16">
<h1> Rate </h1>
<Input type="number" id="r"name="Rate" Size="16">
<h1> Time </h1>
<Input type="number" id="t" name="Time" Size="16">
<input type="button" onClick=intcal() value="Calculate">

1 Answers1

3

A few problems there. getElementById returns a DOM element. You need to grab the value of the element, which is a string, and then convert it to a number (or cast it):

var pr = +document.getElementById("P").value;
var ra = +document.getElementById("r").value;
var ti = +document.getElementById("t").value;

+ casts the string to a number. Now your multiplication should work.

Also you forgot your quotes around the function call on the onclick event. Oh and read on why document.write is bad practice.

Edit: As Bergi said, multiplication casts a number as well, but in any case since you have variables, you probably want numbers assigned to them.

Community
  • 1
  • 1
elclanrs
  • 85,039
  • 19
  • 126
  • 159