简体   繁体   中英

How to make a Font Awesome Icon launch the native browser datepicker?

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?

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM