2

We have that simple date input :

<input type="date" id="inp_DateDep"  />

When the input is clicked, we want the default month displayed to be august.

I could set the minimal value to the first day of the month like so :

<input type="date" id="inp_DateDep" min="2023-08-01" />

But if I do so, then the user won't be able to select a date before the first day of august. In some rare case they will need to select a date in july... but it will more often be august.

In short, is there a way to choose what default month will be displayed in a type="date" input without setting a default value nor using the min attribute ?

InSync
  • 4,851
  • 4
  • 8
  • 30
Antoine Pelletier
  • 3,164
  • 3
  • 40
  • 62

1 Answers1

2

You can add event listeners for focus, change and blur to make the default value appears iff the user hasn't explicitly chosen a date:

const input = document.querySelector('#inp_DateDep');
const defaultDate = '2023-08-01';

input.usingDefault = true;

input.addEventListener('focus', () => {
  if (input.usingDefault) {
    input.value = defaultDate;
  }
});

input.addEventListener('change', () => {
  input.usingDefault = false;
});

input.addEventListener('blur', () => {
  if (input.usingDefault) {
    input.value = '';
  }
});
<input type="date" id="inp_DateDep">

There is a minor problem though: The input may get focused without datepicker being shown. For workarounds, see this question.

Edit: If the default date is chosen, the 'change' event will not be dispatched and the value will be discarded incorrectly. I haven't found an actual workaround, but changing 'change' to 'input' resolves this issue with the exchange of being less strict (moving over months also count as input).

InSync
  • 4,851
  • 4
  • 8
  • 30
  • You edited to remove Jquery and razor tags, now that I think of it, there is no CSS either. It was just so you know that I'm already using these technologies so if you need them to answer feel free to use them. But your answer was pure javascript. Anyway, this works just fine. – Antoine Pelletier Apr 18 '23 at 20:17