javascripthtmltimepickerhtml-input

How do I set the starting value of a time picker, only when it gets focus?


I have a time picker:

<input type="time" name="appt-time">

I want to keep it empty until the user starts selecting a time. Only when the user clicks the element and the popup is shown do I want a default value to be shown.

Is that possible? if so how?


Solution

  • Perhaps this will work for you

    window.addEventListener('DOMContentLoaded',() => {
      const time = "15:05";
      let changed = false;
      const timePicker = document.querySelector('[name="appt-time"]');
      timePicker.defaultValue = null;
      timePicker.addEventListener('focus', (e) => {
        if (!changed) timePicker.value = time;
      });
      timePicker.addEventListener('change', (e) => {
        changed = true;
      });
      timePicker.addEventListener('blur', (e) => {
        if (!changed) timePicker.value = null;
        else timePicker.defaultValue = timePicker.value; 
      });
    });
    <input type="time" name="appt-time">