Domanda

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>
È stato utile?

Soluzione

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top