0

I have a date input, and next to it I have a font awesome. How can I make the font Awesome Icon Launches the default browser datepicker?

<input type="date">
<span (click)="launchHereDatePicker()" class="fa fa-search facturas col-sm-1 "></span>

How could I achieve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Julio Rodríguez
  • 447
  • 1
  • 8
  • 23
  • What would be that default control? – Dalorzo Nov 09 '19 at 03:14
  • So, when you say "default browser datepicker"... are you referring to the fact that you are using a UI framework like Boostrap or jQueryUI which enhances the input fields, and you want to show the plain vanilla HTML date input field? – Mr. Polywhirl Nov 09 '19 at 03:35
  • Similar question that might help you here: https://stackoverflow.com/questions/18326982/open-html5-date-picker-on-icon-click?answertab=votes#tab-top – Word Rearranger Nov 09 '19 at 03:47
  • Similar question solved: https://stackoverflow.com/questions/18326982/open-html5-date-picker-on-icon-click – znxr Nov 09 '19 at 04:27

2 Answers2

1

Most browser will try to focus the form control. In this case, I wrapped the icon in a label that is for the date element. This way the browser knows what to focus. Unfortunately, as of right now, Chrome 78 will focus the control but won't open the date picker so this is not a perfect solution for all browsers but might be enough for your needs.

<input id="date" type="date">
<label for="date">
  <span class="fa fa-search facturas col-sm-1">icon</span>
</label>
Word Rearranger
  • 1,306
  • 1
  • 16
  • 25
  • Almost, but in this case you are focusing the date input; what I'm trying to figure out is the way to launch the date picker as if I had clicked the black arrow when clicking the font awesome. – Julio Rodríguez Nov 10 '19 at 03:31
  • @JulioRodríguez it does open the datepicker on most browsers except Chrome. – Word Rearranger Nov 10 '19 at 04:03
1

So, this works in nearly all current browsers, EXCEPT Chrome for the desktop.

References

addEventListeners('.facturas', 'click', launchDatePicker);

function launchDatePicker(e) {
  let input = e.target.previousElementSibling;
  input.focus();
  input.click();
  // or you can just call this instead... openPicker(input);
}

function addEventListeners(elements, eventName, handler) {
  if (typeof elements === 'string') elements = document.querySelectorAll(elements);
  Array.from(elements).forEach(el => el.addEventListener(eventName, handler));
}

function openPicker(inputDateElement) {
  let event = document.createEvent('KeyboardEvent');
  event.initKeyboardEvent('keydown', true, true, document.defaultView, 'F4', 0);
  inputDateElement.dispatchEvent(event);
}
.facturas {
  cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet" />
<form>
  <input name="some-date" type="date" />
  <span class="fa fa-search facturas col-sm-1"></span>
</form>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132