Search code examples
javascriptjquerydaterangepicker

for daterange picker in the form how to set isinvalid date when already applied the callback function for getting the dates on click of apply button


List item

html form

<div class="form-group " id="input-dates">
<input class="form-control date-range-picker" id="dateRange_n" type="text" name="dates" placeholder="<?php echo get_phrase('when'); ?>.." autocomplete="off" required>
<i class="icon_calendar"></i>

i have used the callback function

    function myCallback(start, end) {
                $('#dateRange_n').html(start.format('MM DD, YYYY') + ' - ' + end.format('MM DD, YYYY'));

        }
    let options = {} // you can add more options to this, but need at least this
$('#dateRange_n').daterangepicker(options, myCallback)
  .on("input change", function(e) {
      var days = e.target.value;
    console.log("Date changed: ",days); });

now i want to use isinvalid date function for disable particular date. i have used the following function on document.ready()

 $('#dateRange_n').daterangepicker({
// you can use this optionally -> maxSpan: 50
 
"startDate": today,
 "endDate": today2,
 "minDate": today,
 isInvalidDate: function(ele) {
    var currDate = moment(ele._d).format('MM-DD-YYYY');
    return ["06-15-2021"].indexOf(currDate) != -1;
}

});

it is working but callback function is not working when i add the above function on document ready


Solution

  • You can pass the callback function after the option.

    Example below

    function myCallback(start, end) {
      console.log("callback");
      $("#dateRange_n").html(
        start.format("MM DD, YYYY") + " - " + end.format("MM D, YYYY")
      );
    }
    
    let options = {
      startDate: "12-01-2018",
      endDate: "12-01-2023",
      minDate: "10-06-2021",
      isInvalidDate: function (ele) {
        var compareDate = moment(ele);
        var startDate = moment("12/01/2019", "DD/MM/YYYY");
        var endDate = moment("5/06/2021", "DD/MM/YYYY");
        return compareDate.isBetween(startDate, endDate);
      },
    };
    
    $("#dateRange_n").daterangepicker(options, myCallback);
    <script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <div class="form-group" id="input-dates">
      <input
        class="form-control date-range-picker"
        id="dateRange_n"
        type="text"
        name="dates"
        placeholder="test...."
        autocomplete="off"
        required
      />
      <i class="icon_calendar"></i>
    </div>