Search code examples
javascriptphpjquerylaraveldatepicker

datepicker days and date logic for jquery


on the on _change event of from_date i want to fetch the value of input days and from_date to add the value of days and from_date and set it to to_date

for example input_days=5 and from_date=10/02/2020 it should add and automatically display 15/02/2020 in to_date....

here is the code which adds from_date and to_date and displays total_date but... what should i change in this logic?

$("#fromdate,#todate").datepicker({
    minDate: 0,
    changeMonth: true,
    changeYear: true,
    firstDay: 1,
    dateFormat: 'yy/mm/dd',
});

$("#fromdate").datepicker({dateFormat: 'yy/mm/dd'});
$("#todate").datepicker({dateFormat: 'yy/mm/dd'});

$('#enddate').change(function () {
    var start = $('#fromdate').datepicker('getDate');
    var end = $('#todate').datepicker('getDate');

    if (start < end) {
        var days = (end - start) / 1000 / 60 / 60 / 24;
        $('#total_days').val(days);
    } else {

        alert("cannot select same or previous date!");
        $('#fromdate').val("");
        $('#total_days').val("");
    }
});

Solution

  • Please refer below code. Also please find fiddle link in comment. If input is blank I am adding 5 days by default.

    <label class="required">Days</label> <input type="text" id="days"><br/><br/><br/>
    <label class="required">from</label>                                                                                                           
    <input type="text" id="fromDate" class="form-control date-picker from input-append minDate" placeholder="mm/yyyy"><br/><br/><br/>
    
    <label> To </label>                                             
    <input type="text" id="toDate" class="form-control date-picker to input-append maxDate" placeholder="mm/yyyy" >
    
    $(function() {
        $( ".from" ).datepicker({
          onSelect: function( selectedDate ) {
            $( ".to" ).datepicker( "option", "minDate", selectedDate );
            var toDate = $('.from').datepicker('getDate');
            var days = $("#days").val()  != "" ? parseInt($("#days").val()) : 5;
                    toDate.setDate(toDate.getDate() + days );
                    $('.to').datepicker('setDate', toDate);
          }
        });
        $( ".to" ).datepicker({
          onSelect: function( selectedDate ) {
            $( ".from" ).datepicker( "option", "maxDate", selectedDate );
          }
        });
      });