Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus month or year of html5 input[type="date"]

I included a fiddle showing what happens when you apply focus to the element, it sets the focus to the 'day' part of the input, but I can't find any documentation on how the DOM renders and identifies each portion of the date.

How can I programmatically focus the month/year portions of an input[type="date"] element, and is there any documentation on how this type of element gets rendered in the DOM?

https://jsfiddle.net/uytdhqax/

<input id="dob" type="date" />
document.getElementById('dob').focus()
like image 339
trickpatty Avatar asked May 06 '15 19:05

trickpatty


Video Answer


2 Answers

This isn't possible in any current implementation of the input[type=date] element as far as I'm aware. Furthermore, different browsers implement this element in different ways, so there is no standalone implementation documentation.

One has to ask why you'd want to imitate this behaviour though. Changing the year value alone will not give the element a value unless the day and month have also been set. In Chrome, at least, if you have an input[type=date] element you'll be shown an element containing placeholder text dd/mm/yyyy. If you select the yyyy part manually and change this to 2015, for example, the input's text will now read dd/mm/2015, but its value will be "" (an empty string). Unless you're manually editing the day and month parts, forcing focus onto the year will not achieve anything other than confusion to users.

like image 127
James Donnelly Avatar answered Sep 21 '22 20:09

James Donnelly


Short answer: it's not supported.

If you try to set selection (focus) using

var el = document.getElementById('dob');
var r = document.createRange();
el.setSelectionRange(r);

you will get the error:

DOMException: Failed to execute 'setSelectionRange' on 'HTMLInputElement': The input element's type ('date') does not support selection.

Also the only documentation I found about date input type says "Not supported", so I thinks there's no such documentation. By now seems that only Chrome implements this input type.

like image 24
Pedro Sanção Avatar answered Sep 22 '22 20:09

Pedro Sanção