Skip to content

Instantly share code, notes, and snippets.

@githubnando
Last active February 22, 2017 12:53
Show Gist options
  • Save githubnando/9337064dedbe01688428ad002af887fd to your computer and use it in GitHub Desktop.
Save githubnando/9337064dedbe01688428ad002af887fd to your computer and use it in GitHub Desktop.
Two date inputs synchronized

Two date inputs using daterangepicker and jQuery. If the first date gets an update, the second date will also suffer an update if the range of the first date is higher than the second one.

example

// this.dateRangePicker('#start_at_datepicker', '#start_at_form');
// this.dateRangePicker('#end_at_datepicker', '#end_at_form', true);

dateRangePicker(datepickerInputId, dateInputId, minDate = false) {
    let input = document.querySelector(dateInputId);

    require(['moment','daterangepicker'], (moment) => {
        let dpconf = {
            locale: {
                singleDatePicker: true,
                showDropdowns: true,
                format: 'DD/MM/YYYY HH:mm',
                firstDay: 1,
            },
            singleDatePicker: true,
            showDropdowns: true,
        };

        if (minDate) {
            dpconf.minDate = moment().format('DD/MM/YYYY');
        } else {
            dpconf.minDate = '01/01/2017';
        }

        $(datepickerInputId).daterangepicker(dpconf, (start) => {
            input.value = start.format('YYYY-MM-DD');

            if (input.getAttribute('name') == 'start_at') {
                dpconf.minDate = start.format('DD/MM/YYYY');
                let endAt = document.querySelector('#end_at');

                $('#end_at_datepicker').daterangepicker(
                    dpconf, start => endAt.value = start.format('YYYY-MM-DD')
                );

                if (moment(start).isAfter(endAt.value)) {
                    endAt.value = start.format('YYYY-MM-DD');
                }
            }
        });
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment