cfDateSelector - simple date selection

by whelkaholism

HTML

<input type="text" id="ds"/>
<p>
</p>
<input type="text" id="dp"/>

CSS

.cf-dateselector { display: flex; align-items: centre }

select.cf-dsctor-part {
  font-size: 16px;
  padding: 10px;
  margin-right: 5px;
}

select.cf-dsctor-part.yc {
  padding-right: 0;
  border-right: none;
  margin-right: 0;
} 

select.cf-dsctor-part.yd {
  padding-left: 0;
  border-left: none;
  margin-left: 0;
}

JavaScript

(function()
{
    window.cfDateSelector = function(el, options) 
    {
        var _this = this;
        var _options = options || {};

        var _now = new Date();
        _options.firstYear = _options.firstYear || (_now.getUTCFullYear() - 120);
        _options.lastYear = _options.lastYear || _now.getUTCFullYear();
        _options.allowClear = typeof (_options.allowClear) != 'undefined' ? _options.allowClear : true;;

        var _container;
        var _d;
        var _m;
        var _yc;
        var _yd;
        var _clear;

        this.setDateISO = function(isodate)
        {
            var jsdate = !!isodate ? new Date(isodate) : null;

            if (jsdate && !isNaN(jsdate))
                _this.setDate(jsdate);
            else
                _clearDate();
        };

        this.setDate = function(jsdate)
        {
            _d.value = _pad(jsdate.getDate());
            _m.value = _pad(jsdate.getMonth() + 1);
            var c = Math.floor(jsdate.getFullYear() / 100) * 100;
            _yc.value = _pad(c / 100);
            _yd.value = _pad(jsdate.getFullYear() - c);
        };

        this.getYear = function()
        {
            return _yc.value != '' && _yd.value != '' ? (parseInt(_yc.value, 10) * 100) + parseInt(_yd.value, 10) : NaN;
        };

        this.getMonth = function()
        {
            return _m.value != '' ? parseInt(_m.value, 10) : NaN;
        };

        this.getDate = function()
        {
            return _d.value != '' ? parseInt(_d.value, 10) : NaN;
        };

        this.onDateSelected = function(jsdate)
        {
            var dd = _d.value;
            var mm = _m.value;
            var yyyy = _yc.value + _yd.value;
            var ds = `${dd}/${mm}/${yyyy}`;

            el.value = ds;

            _options.selected && _options.selected({ dd, mm, yyyy, js: jsdate });
        };

        this.onInvalidDateSelected = function(jsdate)
        {
            el.value = '';

            _options.selected &&...