user3304303
user3304303

Reputation: 1043

How to change datepicker options based on a checkbox?

I have a jQuery UI datepicker on which I only want dates 5-days-out (or more) to be available. This works fine for that:

var dateToday = new Date(); 
$( "#datepicker" ).datepicker({
    minDate: '+1w', // your min date
    beforeShowDay: $.datepicker.noWeekends // disable weekends
}); 

I also have a checkbox that, if checked, essentially overrides the minDate and makes the minDate available today's date (rather than a week out):

<input type="checkbox" class="lessThanFiveDays" value="1" name="less-than-5-days" />I need this earlier than the standard 5 business days   

I'm struggling with where the checkbox checking jQuery needs to go and in what order. Also, do I just check if the box is checked, or does the altering of the datepicker params need to happen on a "change" event on the checkbox?

This below is wrong, but hopefully it helps illustrate how I'm confusing myself:

$( "#datepicker" ).datepicker({
    minDate: '+1w', // your min date
    beforeShowDay: $.datepicker.noWeekends // disable weekends*/
});
$('.lessThanFiveDays').change(function() {
    if($(this).is(":checked")) {
        $( "#datepicker" ).datepicker({
            minDate: dateToday, // your min date
            beforeShowDay: $.datepicker.noWeekends // disable weekends*/
        });
    }
});

Upvotes: 0

Views: 1008

Answers (2)

VincenzoC
VincenzoC

Reputation: 31502

You don't need to re-initialize the datepicker, you can just use minDate function in the checkbox change handler.

Here a working example:

var dateToday = new Date(); 
$( "#datepicker" ).datepicker({
  minDate: '+1w',
  beforeShowDay: $.datepicker.noWeekends
});
$('.lessThanFiveDays').change(function() {
  if( $(this).is(":checked") ) {
    $("#datepicker").datepicker("option", "minDate", dateToday);
  } else {
    $("#datepicker").datepicker("option", "minDate", '+1w');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.css" rel="stylesheet"/>

<input type="text" id="datepicker">
<input type="checkbox" class="lessThanFiveDays" value="1" name="less-than-5-days" />I need this earlier than the standard 5 business days

Upvotes: 2

blgt
blgt

Reputation: 8205

The datepicker is already initialised, so the second call to the initialiser won't work. Use the option method instead, as in http://api.jqueryui.com/datepicker/#option-minDate:

$("#datepicker").datepicker("option", "minDate", dateToday);

Example: https://jsfiddle.net/dets1x11/

Upvotes: 3

Related Questions