0

I just started learning html yesterday and now I am trying to create a website that can compute a simple math problem. The website works but when I try to enter a decimal number the result becomes NaN. I do not know how can I enter decimal numbers without getting NaN.

This is my whole html code:

var mwInput, tInput, dx1, dx2, dy1, dy2, vx1, vx2, vy1, vy2, diameterInput, velocityInput;
var validationText, densityResult, viscosityResult, nreResult;

function calculate() {
  mwInput = document.forms["inputs"]["mwInput"].value;
  tInput = document.forms["inputs"]["tInput"].value;
  dx1 = document.forms["inputs"]["dx1"].value;
  dx2 = document.forms["inputs"]["dx2"].value;
  dy1 = document.forms["inputs"]["dy1"].value;
  dy2 = document.forms["inputs"]["dy2"].value;
  vx1 = document.forms["inputs"]["vx1"].value;
  vx2 = document.forms["inputs"]["vx2"].value;
  vy1 = document.forms["inputs"]["vy1"].value;
  vy2 = document.forms["inputs"]["vy2"].value;
  diameterInput = document.forms["inputs"]["diameterInput"].value;
  velocityInput = document.forms["inputs"]["velocityInput"].value;
  densityResult = (dy1 + (tInput - dx1) * ((dy2 - dy1) / (dx2 - dx1))) * mwInput;

  document.getElementById("density").innerHTML = densityResult;

}
<form name="inputs" action="javascript:calculate();">
  <span>MW of Substance: </span>
  <input type="text" name="mwInput"><br>
  <span>Enter value of T: </span>
  <input type="text" name="tInput"><br>
  <span>Density</span><br>
  <span>X</span>
  <span>Y</span><br>
  <input type="text" name="dx1">
  <input type="text" name="dy1"><br>
  <input type="text" name="dx2">
  <input type="text" name="dy2"><br><br>
  <span>Viscosity</span><br>
  <span>X</span>
  <span>Y</span><br>
  <input type="text" name="vx1">
  <input type="text" name="vy1"><br>
  <input type="text" name="vx2">
  <input type="text" name="vy2"><br><br>
  <span>Inside diameter: </span>
  <input type="text" name="diameterInput"><br><br>
  <span>Velocity: </span>
  <input type="text" name="velocityInput">
  <br><br>
  <input type="submit" value="Calculate">
</form>

<p id="validation">
  <p id="density"></p>
  <p id="viscosity"></p>
  <p id="nre"></p>
j08691
  • 204,283
  • 31
  • 260
  • 272
akolangto
  • 33
  • 1
  • 6
  • 2
    Swap the operands of the `+` in your formula and it should work. Better is to explicitly convert all values you get from inputs from string to number, using the unary plus. – trincot May 28 '21 at 14:34
  • 1
    I have made it like this "densityResult = (+dy1 + (+tInput-+dx1) * ((+dy2-+dy1)/(+dx2-+dx1))) * +mwInput;" and now it works. – akolangto May 28 '21 at 14:35
  • 2
    Good. You'll make it more readable if you move those unary `+` operations to the assignments you made above, like `dx1 = +document.forms["inputs"]["dx1"].value`. – trincot May 28 '21 at 14:46
  • I have completed it but when the answers shows, the form moves to the right. Any fix for that? – akolangto May 28 '21 at 14:58

0 Answers0