-1

So I made this very basic form with just 4 inputs fields and a submit button with the value and onclick function "calculate".

Then I started coding some javascript for it that looks like this:

function calculate(){
var insert1 = document.getElementById('insert1').value;
var insert2 = document.getElementById('insert2').value;
var insert3 = document.getElementById('insert3').value;
var isnert4 = document.getElementById('insert4').value;

var results = insert1 * insert2 * insert3 * insert4;
document.write(results);
}

So I tested the code by pressing on the submit button and it only displayed "NaN". I noticed that when I change the parameter of the document.write to one of the inserts I don't get the error and it will display the value of the insert. So i think that the issues is in the var result line but i'm not 100% sure.

mg19
  • 5
  • 1
  • 3
  • Maybe try [debugging your code](http://stackoverflow.com/questions/988363/how-can-i-debug-my-javascript-code) – Liam May 11 '17 at 09:47
  • 2
    You need to provide a real [mcve]. The code you have given will throw a referenceerror, not display NaN (so you haven't verified it). A *complete* example would need to include the HTML and the data you were testing. – Quentin May 11 '17 at 09:48
  • Ahhhh, it won't throw a referenceerror because `insert4` et al are globals implicitly created by the input elements. (That would have been more obvious if the [mcve] was complete) – Quentin May 11 '17 at 10:01
  • there is a small typo at `var insert4` you wrote typed `var isnert4` thats – Taku_VM Jun 23 '20 at 18:56

1 Answers1

0

The reason you're getting a NaN is because attempting to multiply anything with NaN yields another NaN.

Due to a typo in your code:

var isnert4 = document.getElementById('insert4').value; 
     ^ --- here

But attempting to use the variable you intended:

var results = insert1 * insert2 * insert3 * insert4;
                              here ------------^

Means insert4 is NaN and thus the result of the entire calculation is also NaN.

Correct the typo and your code will work as expected.

ps. Its 2017, stop using document.write!

Jamiec
  • 133,658
  • 13
  • 134
  • 193