The one and only datepicker solution

by Bianca Kuehweidner

HTML

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Dates : 
<input type="text" id="myDate" class="datepicker" data-nextelem="#myDate2"  data-mindate="-20" maxlength="10" style="width:80px" /> -

<input type="text" id="myDate2" class="datepicker" data-prevelem="#myDate" data-nextelem="#myDate3"  maxlength="10" style="width:80px"/> -

<input type="text" id="myDate3" class="datepicker" data-prevelem="#myDate2"  data-maxdate="+2y" maxlength="10" style="width:80px"/>

JavaScript

$(function(){
	initDatePicker();
})


function initDatePicker(){

	// do a loop for custom property on each element
	$('.datepicker').each(function(){
    
    // you can find available formats here : http://api.jqueryui.com/datepicker/#utility-formatDate
		$(this).datepicker({
			dateFormat:'mm/dd/yy'
	    });
      
		// set minimum date from data attribute. 
		if (typeof $(this).data('mindate') != 'undefined') {
			$(this).datepicker('option','minDate',$(this).data('mindate'));
		}
    
		// set maximum date from data attribute. 
		if (typeof $(this).data('maxdate') != 'undefined') {
			$(this).datepicker('option','maxDate',$(this).data('maxdate'));
		}
		
		$(this).on('change',function(){
			parseInputDate(this);
      
			// now, set date relations :) 
			if (typeof $(this).data('nextelem') != 'undefined') {
				$($(this).data('nextelem')).datepicker( "option", "minDate", getDate( this ) );
			}
			if (typeof $(this).data('prevelem') != 'undefined') {
				$($(this).data('prevelem')).datepicker( "option", "maxDate", getDate( this ) );
			}
		});
		
	});
}

// get date function taken from : http://jqueryui.com/datepicker/#date-range
function getDate( element ) {
  var date;
  try {
		date = $.datepicker.parseDate( $(element).datepicker('option','dateFormat'), element.value );
  } catch( error ) {
		date = null;
  }
  return date;
}

function parseInputDate(elm) {
  var currDate = new Date(),
      monDt = (('0'+(currDate.getMonth()+1)).slice(-2)+('0'+currDate.getDate()).slice(-2)), // get current month+date to compare
      inputVal = $(elm).val().match(/\d{2}/gi), // split date components into array of [dd,mm,yy,yy]
      format = $(elm).datepicker("option", "dateFormat"); // get current element's datepicker format
      
  // check if it's already a valid entry, then do nothing 
  if ($(elm).val() == $.datepicker.formatDate(format,$(elm).datepicker('getDate'))) return;    
  
  var isValidDate = function(yyyy,mm,dd) {
	var dt = new...