5

I have two date input one with start date and other is an end date. I want to set minDate Dynamically to end date input based on start date. In short, I want to prevent a user from selecting end date less than start date (on change of start date I want to update minDate property for end date input).

<input type="text" id="start_date" class="form-control"  name="start_date" data-input="date-range" >
<input type="text" id="end_date" class="form-control"  name="end_date" data-input="date-range" >

    $('[data-input=date-range]').each(function(index, picker) {
            $(picker).daterangepicker({
                alwaysShowCalendars: true,
                showCustomRangeLabel: true,
                startDate: picker.value ? moment(picker.value, "YYYY-MM-DD hh:mm:ii") : moment(),
                singleDatePicker: true,
                showDropdowns:true,
                autoUpdateInput: true,
                locale: {
                    cancelLabel: 'Clear',
                    format: 'MMMM D, YYYY'
                },
            });
        });

I am using daterangepicker in a form

Jigar
  • 3,055
  • 1
  • 32
  • 51

1 Answers1

8

bind an onChange event listener to the start_date input and inside the handler, fetch the start_date's value and add one more day using moment js, since you are already using it.

Then reinitialize the end_date calendar input with a minDate (Link) property like below. so that previous dates less than 1 day from the start can't be selected.

$('#start_date').on('change', function(){
    $('#end_date').daterangepicker({
            alwaysShowCalendars: true,
            showCustomRangeLabel: true,
            minDate:moment($('#start_date').val(), "MMMM D, YYYY").add(1, 'd');
            singleDatePicker: true,
            showDropdowns:true,
            autoUpdateInput: true,
            locale: {
                cancelLabel: 'Clear',
                format: 'MMMM D, YYYY'
            },
});

make sure you use appropriate formats while parsing the date using moment.

Edit: it seems you can mutate the object directly without reinitializing

$('#end_date').data('daterangepicker').minDate = new_date_you_obtained
Shobi
  • 10,374
  • 6
  • 46
  • 82
  • you are reinitializing that input but actually i don't want to do this I want to use the previous object and want to update minDate dynamically. – Jigar Jan 24 '19 at 06:24
  • I don't think you can mutate the daterange picker once initialized – Shobi Jan 24 '19 at 06:25
  • 2
    please check the updated answer for directly modifying the properties – Shobi Jan 24 '19 at 12:25