tonydeleon
tonydeleon

Reputation: 151

How can I add one more day to the Jquery UI Datepicker date range?

I have this code that works fine if I enter the dates, but if I click on ".from_date" and leave it empty, I have this error: "Cannot read property 'setDate' of null". What could I do to avoid the error?

    $(".from_date").datepicker({
      minDate: 0,
      dateFormat: "dd/mm/y",
      defaultDate: "+1w",
      numberOfMonths: 1,
      onClose: function() {
      var minDate = $(this).datepicker('getDate');
      var newMin = new Date(minDate.setDate(minDate.getDate() + 1));
        $(".to_date").datepicker("option", "minDate", newMin);
        return $(".to_date").datepicker("show");
      }
    });
 $(".to_date").datepicker({
      minDate: '+1D',
      dateFormat: "dd/mm/y",
      defaultDate: "+1w",
      numberOfMonths: 1
    });

Upvotes: 0

Views: 167

Answers (1)

Twisty
Twisty

Reputation: 30883

Consider the following example.

$(function() {
  $(".from_date").datepicker({
    minDate: 0,
    dateFormat: "dd/mm/y",
    defaultDate: "+1w",
    numberOfMonths: 1,
    onClose: function(dText) {
      var minDate = $.datepicker.parseDate("dd/mm/y", dText);
      if (minDate != null) {
        var newMin = new Date(minDate.setDate(minDate.getDate() + 8));
        $(".to_date").datepicker("option", "minDate", newMin);
      }
    }
  }).datepicker("setDate", "+1w");
  $(".to_date").datepicker({
    minDate: "+8d",
    dateFormat: "dd/mm/y",
    defaultDate: "+8d",
    numberOfMonths: 1
  }).datepicker("setDate", "+8d");;
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="from">From</label>
<input type="text" id="from" class="from_date" name="from">
<label for="to">to</label>
<input type="text" id="to" class="to_date" name="to">

Here, we pre-populate a date with setDate method. This ensures that there is a Date in either field so if the User selects a date or does not, they can proceed without error.

Upvotes: 1

Related Questions