Web components are very useful here, but they are not yet fully supported in all browsers.
The idea is to create a simple html element with two children (from and to) as follows:
<div id="fromToDate"> <div></div> <div></div> </div>
then create a template that defines what the date caretaker should look like:
<template id="fromToDateTemplate"> <label for="fromDate">from</label> <input type="date" class="fromDate" select=":first" required="" /> <label for="toDate">to</label> <input type="date" class="toDate" select=":last" required="" /> </template>
the select parameter determines where the value is taken from so that the first input field takes the first div from "#fromToDate".
Finally, we need to fill in the "shadow root" and define the logic:
var shadow = document.querySelector('#fromToDate').webkitCreateShadowRoot(), template = document.querySelector('#fromToDateTemplate'); shadow.appendChild(template.content); shadow.querySelector(".fromDate").addEventListener("change", function (e) { var to = this.value; shadow.querySelector(".toDate").setAttribute("min", this.value); }); template.remove();
At the end, the two input fields are renderd and when selecting a date in the first datepicker, the second datepicker cannot select any lower data.
Fiddler example: http://jsfiddle.net/cMS9A/
Benefits:
- Build as a widget
- Easy to repeat
- won't paginate
- can be issued independently
Disadvantages:
- Not supported in all browsers.
Future reading:
source share