I want to keep it empty until the user starts selecting a time. Only when the user clicks t" /> I want to keep it empty until the user starts selecting a time. Only when the user clicks t" /> I want to keep it empty until the user starts selecting a time. Only when the user clicks t"/>

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

89 Views Asked by At

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?

1

There are 1 best solutions below

7
mplungjan On BEST ANSWER

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">