in daterangepicker how can i set minDate Dynamically?
Asked Answered
D

1

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

Distort answered 24/1, 2019 at 6:8 Comment(0)
S
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
Semmes answered 24/1, 2019 at 6:19 Comment(3)
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.Distort
I don't think you can mutate the daterange picker once initializedSemmes
please check the updated answer for directly modifying the propertiesSemmes

© 2022 - 2024 — McMap. All rights reserved.