-2

Its been a few months since I graduated from a tech school (HS level) for programming, and my JavaScript is a bit rusty. I'm just trying to calculate Y%X=Z with textbox inputs. However Z always results in NaN, so I'm assuming my problem is the parsing.

<html>
<body>
<b>Y: </b><input type="text" id="numY" /><br>
<b>X: </b><input type="text" id="numX" /><br>
<h2>Y % X = Z</h2>
<button onclick="myFunction()">Calculate</button>
<h3><p id="demo"></p></h3>
<script>
function myFunction()
{
var y=document.getElementById('numY');
var x=document.getElementById('numX');
var z=parseInt(y)%parseInt(x);
var demoP=document.getElementById("demo")
demoP.innerHTML="z=" + z;
}
</script>

</body>
</html>
nbanic
  • 1,270
  • 1
  • 8
  • 11

1 Answers1

2

x and y refer to the <input> elements, not to their values:

var y = document.getElementById('numY').value;

Also, pass the radix/base argument to parseInt. You want it to be explicit that you're working in base 10:

var z = parseInt(y, 10) % parseInt(x, 10);
Blender
  • 289,723
  • 53
  • 439
  • 496
  • thanks, but to clarify; using that method would I still need to use parseInt() within my calculation of Z? – Brandon Durst Aug 11 '13 at 14:47
  • @BrandonDurst you could use the unary `+` operator to make them integers, if you prefer: `z = +y % +x` – Dave Aug 11 '13 at 14:49
  • @BrandonDurst: Using the modulo operator will coerce both inputs into numbers. – Blender Aug 11 '13 at 14:50
  • @Blender numbers, but not necessarily integers (and it occurs to me that `+` will do the same. Better to use `|0`) – Dave Aug 11 '13 at 15:33
  • @Dave: That'll restrict it to the signed 32-bit range. `parseInt` is the proper tool. – Blender Aug 11 '13 at 16:03