Search code examples
javascriptjquerydatepickerdatetimepicker

JQuery Datepicker/Datetimepicker - How to set MaxDate in java according to a selected option


I'm not so good in Javascript - but I'm trying this:

I had a list of events, where the user can "program to close" the event in a future date.

but, this future date cannot be after the event.

Then, I need to set a maxdate for each event.

I am using JQuery DatePicker - and to set the maxdate I do this:

    $('#closeevent').datetimepicker({
    minDate: 0,
    maxDate: new Date(2016, 8, 15, 8, 0)
});

maxDate = 2016/8/15 08:00

My problem:

How I can change the "2016, 8, 15, 8, 0" (maxDate value) onClick a button for each event (because each event has a different maxDate.

event 1 ... maxDate (2016, 9, 10, 8, 0) .... [button onClick:..] event 2 ... maxDate (2016, 10, 22, 10, 30) .... [button onClick:..]

If I click Button for event1 - the maxDate change to 2016, 9, 10, 8, 0..

If I click button for event2 - the maxDate change to 2016, 10, 22, 10, 30..

tks a lot


Solution

  • You can use the beforeShowDay property to assign a function that is called before each date is displayed. The return allows you to control days with a much higher granularity.

    You can look at this fiddle for an example. https://jsfiddle.net/tv760t1s/

    var maxDate = new Date(2016, 8, 15, 8, 0);
    $(".dateChange").click(function() {
      maxDate = new Date($(this).attr('value'));
      console.log(maxDate);
    });
    $("#datepicker").datepicker({
      minDate: 0,
      maxDate: new Date(2016, 8, 15, 8, 0),
      beforeShowDay: function(date) {
        console.log(date, maxDate);
        if (date > maxDate) {
          return [false, 'noShowClass', 'Date time not available'];
        } else {
          return [true, '', ''];
        }
      }
    });
    

    The HTML:

    <div>    
      <input type='text' id='datepicker' value=''>
      <input class='dateChange' type='button' value='2016-08-15 08:00:00'>
      <input class='dateChange' type='button' value='2016-09-10 08:00:00'>
    </div>