Q:

I cannot obtain numerical values from input elements, even using parseInt

I am making a speed calculator where you enter the numbers and you get a speed.
here is the code...
<html>
<head><title>speed</title></head>
<body>
<font face="arial">
<h1>Speed Calculator</h1>
<form>
distance: <input type="text" size="3" id="distance">
</form>
time: <input type="text" size="3" id="hours"> Hours
<pre>
<pre>
<input type="button" value="Speed" id="button">
<script>
var dist = parseInt(document.getElementById("distance").value, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
var speed = parseInt(dist, 10) + parseInt(hours, 10);
var button = document.getElementById("button");
button.onclick = function () {
    alert("the speed you were traveling is " + speed + "mph")
}
</script>
</font>
<body>
<html>

I enter the numbers but it returns "the speed you were traveling is NaNmph".
Is there a way to fix this?

A:

This will retrieve the values of the form fields when the page is loaded and they're still empty.  You need to set those variables inside the button.onclick function instead, so they get the values of the fields as of the time the button is pressed.
You only need to parseInt the values once.

