NotGood_
NotGood_

Reputation: 11

Jquery DatePicker Set min and max date

I am trying to make a webpage which has a datepicker, but i can not figure out how i can set the min and max date dynamically.I am trying to achieve is

  1. not let the user select a date before today's date.
  2. Once a date is selected set the max selectable date to 1 week, so the user can only choose from 7 days the selected date.
    So far I have done this, but it does not seem to update every time a user selects a new date. for example, if i select today's date (23) it does set the max date to 29, but if i change my selected date from 23 to 27, rather than it letting me choose from 27 to 3, it only allows me to select from 27 to 29. can someone please help me? thanks :)

$(document).ready(function() {
           
  $(function() {
      $('#txtArrivalDate').datepicker({
          dateFormat: 'mm-dd-yy',
          minDate: "-0d",
          onSelect: function(date) {
              selectedDate = date;
              $('#txtDepartureDate').datepicker('option', 'minDate', date);
              $("#txtDepartureDate").datepicker("refresh");
              $('#txtDepartureDate').datepicker('option', 'firstDay', date);
              $('#txtDepartureDate').datepicker('option', 'maxDate', '+7d');
          }, //end of onSelect attribute

          onClose: function(date) {
          }, //end of onClose

      }); //end of txtArrivalDate datepicker
  }); //end of txtArrivalDate function

  $("#txtArrivalDate").change(function() {

      $('#txtDepartureDate').datepicker('option', 'firstDay', selectedDate);
      $('#txtDepartureDate').datepicker('option', 'maxDate', '+7d');
  });

  $(function() {
      $('#txtDepartureDate').datepicker({
          dateFormat: 'mm-dd-yy'
      });
  }) //end of txtDepartureDate function

}); //end of Ready function
<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>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Arrival Date:-
  <input type="text" id="txtArrivalDate" /> <br /><br />
Departure Date:-
  <input type="text" id="txtDepartureDate" /> <br /><br />

Upvotes: 1

Views: 5934

Answers (1)

Rajen Trivedi
Rajen Trivedi

Reputation: 1302

Try this code

$(document).ready(function(){
    $('#txtArrivalDate').datepicker({
        dateFormat: 'mm-dd-yy',
        minDate : "-0d",
    });

    $('#txtArrivalDate').change(function(){
        var sDate = $(this).datepicker("getDate");
        var minDate = $(this).datepicker("getDate");
        sDate.setDate(sDate.getDate()+7);
        $('#txtDepartureDate').datepicker({
            dateFormat: 'mm-dd-yy',
            maxDate : sDate,
            minDate : minDate,
        });
    })
});

Good Luck..

Upvotes: 2

Related Questions