Search code examples
javascripttruncation

document.getElementById().value truncating the seconds if it is 0


I'm a javascript newbie and I'm having a bit of trouble with the following:

function log_time() {
    let time = document.getElementById("time").value;
    console.log(time);
}
<input class="input-field" type="time" id="time" onchange="log_time()" step="1">

The format of the value is as follows HH:MM:SS however when the seconds are 00, it gets truncated off completely and the resulting time variable becomes HH:MM.

Is there a way to prevent the seconds from being truncated or a check to format the value if the seconds are being truncated?


Solution

  • How about something like this?

    const timeElement = document.getElementById("time")
    
    timeElement.addEventListener('change', (e => {
      // extract e.target.value as timeVal with default value "00:00:00"
      const {target: {value: timeVal = "00:00:00"} = {}} = e || {};
    
      // extract hours, minutes, seconds from the split array.
      const timeValArray = timeVal.split(":");
      const [hours, minutes, seconds = "00"] = timeValArray;
    
      console.log("hours: ", hours)
      console.log("minutes: ", minutes)
      console.log("seconds: ", seconds)
    }
    ));
    

    Output:

    hours:  17
    minutes:  13
    seconds:  00