Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datepicker - refresh pickable days based on selected option

I have a select box where the user can pick 3 different shops. It shouldn't be possible to pick weekends for shop 2 and 3, and for shop 1 you should only be able to pick Mon - Sat.

The following javascript only works on the first pick. If you choose another shop right after, it will stick with the old options.

I've tried using $( "#datepicker" ).datepicker("refresh"); (see how to refresh datepicker?) but without any success. I'm starting to think that the problem lies elsewhere.

Javascript:

$(function() {

  var setting, currentShop = 0;

  /* Select box */

  $('select#shop').change(function() {
    (currentShop = $(this).val() == 1) ? loadDatePicker(setting = 'noSunday') : loadDatePicker(setting = 'noWeekends');
  });

  /* Datepicker */

  function noSunday(date){ 
    var day = date.getDay(); 
    return [(day > 0), '']; 
  }

  function loadDatePicker(setting) {
    if(setting == 'noWeekends') {
      $( "#datepicker" ).datepicker({ beforeShowDay: $.datepicker.noWeekends, minDate: +2, maxDate: "+1M" }); 
    }
    if(setting == 'noSunday') {
      $( "#datepicker" ).datepicker({ beforeShowDay: noSunday, minDate: +2, maxDate: "+1M" }); 
    }
    $( "#datepicker" ).datepicker("refresh");
  }
});

HTML:

  <select id="shop" name="shop">
    <option value="0" selected="selected">Choose a shop</option>
    <option value="1">1 (closed sundays)</option>
    <option value="2">2 (closed weekends)</option>
    <option value="3">3 (closed weekends)</option>
  </select>
  <label for="datepicker">Datepicker</label><input type="text" name="date" id="datepicker" value="" readonly="readonly" />

Jsfiddle: http://jsbin.com/ajavek/1/edit

How do I refresh/apply the settings correctly with datepicker?

like image 852
estrar Avatar asked Mar 08 '13 14:03

estrar


2 Answers

See this: DEMO

  function loadDatePicker(setting) {
    $("#datepicker").datepicker("destroy");
    if(setting == 'noWeekends') {
      $( "#datepicker" ).datepicker({ beforeShowDay: $.datepicker.noWeekends, minDate: +2, maxDate: "+1M" }); 
    }
    else if(setting == 'noSunday') {
      $( "#datepicker" ).datepicker({ beforeShowDay: noSunday, minDate: +2, maxDate: "+1M" }); 
    }
    $( "#datepicker" ).datepicker("refresh");
  }

You need to put $("#datepicker").datepicker("destroy"); each time before changing settings...

like image 80
Anujith Avatar answered Sep 18 '22 11:09

Anujith


$("#datepicker").datepicker("destroy");

Above line work for clearing the datepicker.

like image 32
Atik Fahm Avatar answered Sep 19 '22 11:09

Atik Fahm