I'm building a form where one of the fields gets the value of a stopwatch countdown. When stopped, the time elapsed should be submitted as part of the data. The stopwatch JS function works perfectly if rendered as an H1, but doesn't work when I try to render the same countdown as a form input value and I have no idea why. Any help would be greatly appreciated. Specifically, it's the input value (incrementing digits) that does not render at all..it remains blank. A test function will work to alert "hello" as the onclick
, but the desired function does not, though the same thing works outside the form. Here's my code:
// Define vars to hold time vakues
let seconds = 0;
let minutes = 0;
let hours = 0;
// Define var to hold setinterval function
let interval = null;
// Define var to hold stopwatch status
let status = "stopped";
// Stopwatch logic to determine when to increment next value, etc.
function stopwatch() {
seconds++;
// logic to determine when to increment next value
if (seconds / 60 === 1) {
seconds = 0;
minutes++;
if (minutes / 60 === 1) {
minutes = 0;
hours++;
}
}
// If seconds/minutes/hours is only one digit, add a leading 0 to the values
if (seconds < 10) {
displaySeconds = "0" + seconds.toString();
} else {
displaySeconds = seconds.toString();
}
if (minutes < 10) {
displayMinutes = "0" + minutes.toString();
} else {
displayMinutes = minutes.toString();
}
if (hours < 10) {
displayHours = "0" + hours.toString();
} else {
displayHours = hours.toString();
}
// Display updated time values (increments in real time) to user
document.getElementById("display").value = displayHours + ":" + displayMinutes + ":" + displaySeconds;
}
// Function to start / stop the watch
function startStop() {
if (status === "stopped") {
// Start the Stopwatch (by calling the setInterval function)
interval = window.setInterval(stopwatch, 1000);
// Changes "start" button to "stop" button
document.getElementById("startStop").innerHTML = "Stop";
document.getElementById("startStop").style = "background: red";
status = "started";
} else {
window.clearInterval(interval);
document.getElementById("startStop").innerHTML = "Start";
status = "stopped";
}
}
// Function to reset the Stopwatch
function reset() {
window.clearInterval(interval);
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById("duration").value = "00:00:00";
// Changes "stop" button to "start" button
document.getElementById("startStop").innerHTML = "Start";
}
<form action="success.php" method="post">
<label for="session-duration" class="form-label">duration: </label>
<input type="text" name="session-duration" id="duration">
<button type="button" name="button" id="startStop" onclick="startStop()">Start</button>
<button type="button" name="button" id="reset" onclick="reset()">Reset</button>
<input type="submit" name="session-submit" value="SUBMIT">
</form>