Function Keeps Returning Zero

Function Keeps Returning Zero
0.0 0

#1

I’m trying to make a function that will take input from three boxes (hours, minutes, and seconds) so that I can add convert them to seconds and add them together, allowing me to later perform calculations on the number of seconds. Right now, I’m only trying to display the total number of seconds in the input box next to long-fast, but it keeps returning 0. Can someone help me with this? Also, does anyone have suggestions to clean up the code a little bit?

<form name="trainingPaces">
 <fieldset>
  <legend>Renato Canova's Training Paces</legend>
  <label>Time:</label>
  <br>
  <input type="text" name="thour" maxlength="2" size="2" placeholder="hh" onchange="totalTime();">
  <input type="text" name="tmin" maxlength="2" size="2" placeholder="mm" onchange="totalTime();">
  <input type="text" name="tsec" maxlength="2" size="2" placeholder="ss" onchange="totalTime();">
  <table>
   <tr>
    <td></td>
    <th>pace/mi</th>
    <th>pace/km</th>
    <th>s/400</th>
   </tr>
   <tr>
    <th>Regeneration</th>
    <td></td>
    <td></td>
    <td></td>
   </tr>
   <tr>
    <th>Long-Fast (Fundamental)</th>
    <td><input type="text" name="longFastSpeed" readonly></td>
    <td></td>
    <td></td>
</tr>
</table>
</fieldset>
</form>

<script>
var thour = document.trainingPaces.thour.value;
var tmin = document.trainingPaces.tmin.value;
var tsec = document.trainingPaces.tsec.value;

function totalTime() {
	var totalTime =
		(3600 * thour) + (60 * tmin) + (tsec);
	var dist = 1;
	var actualPace = totalTime / 60;
	document.trainingPaces.longFastSpeed.value = actualPace;
}
</script>

#2

If you look at the javascript and when the code is executed you will notice that this part

var thour = document.trainingPaces.thour.value;
var tmin = document.trainingPaces.tmin.value;
var tsec = document.trainingPaces.tsec.value;

is called directly when the document is loaded and never again. The value of the elements at the time of calling is and empty string, and since you are multiplying the values later this empty string gets coerced into the number 0.

Maybe the script should check the values of the input fields at a different time than the document loading?


#3

Thank you so much!!! I put the code inside the function, and it worked like a charm.


#4

Glad to hear you figured it out!