Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datepicker for web page that can allow only specific dates to be clicked

Is there a Javascript or some library that would create a datepicker for a webpage (similar to Jquery UI DatePicker that would only allow certain dates to be clickable and highlighted.

For example on server side, I could specify a array of days to enable to be selected.

like image 927
The Unknown Avatar asked Dec 11 '09 19:12

The Unknown


People also ask

How do I restrict date in DatePicker?

You can restrict the users from selecting a date within the particular range by specifying MinDate and MaxDate properties. The default value of MinDate property is 1/1/1920 and MaxDate property is 12/31/2120 . Dates that appears outside the minimum and maximum date range will be disabled (blackout).

How do you make a DatePicker not editable?

readOnly={true} disables DatePicker instead of preventing edit (and keyboard appearing on mobiles) #1480.


2 Answers

The Datepicker beforeShowDay() event is intended for exactly this purpose. Here's an example where the set of allowed dates is relatively small for purposes of illustration. Depending on how many dates you have and how they are chosen, you could instead write a method that programmatically selected dates (say by ignoring weekends, the 1st and 15th of every month, etc). Or you could combine both techniques, say remove weekends and a fixed list of holidays.

$(function() {
    // this could be a static hash, generated by the server, or loaded via ajax
    // if via ajax, make sure to put the remaining code in a callback instead.
    var dates_allowed = {
          '2009-12-01': 1,
          '2009-12-25': 1,
          '2010-09-28': 1,
          '2011-10-13': 1
    };

    $('#datepicker').datepicker({
        // these aren't necessary, but if you happen to know them, why not
        minDate: new Date(2009, 12-1, 1),
        maxDate: new Date(2010, 9-1, 28),

        // called for every date before it is displayed
        beforeShowDay: function(date) {

            // prepend values lower than 10 with 0
            function addZero(no) {
                if (no < 10){
                  return "0" + no;
                }  else {
                  return no; 
                }
            }

            var date_str = [
                addZero(date.getFullYear()),
                addZero(date.getMonth() + 1),
                addZero(date.getDate())      
            ].join('-');

            if (dates_allowed[date_str]) {
                return [true, 'good_date', 'This date is selectable'];
            } else {
                return [false, 'bad_date', 'This date is NOT selectable'];
            }
        }
    });
});

The return values are

[0]: boolean selectable or not,
[1]: CSS class names to apply if any (make sure to return '' if none),
[2]: Tooltip text (optional)

Note that the date variable given in the callback is an instance of a Date object representing the given day, not a text version of that date in the specified format. So for instance, you could generate the list of allowable dates in one format while displaying dates in the datepicker in a different format (e.g. so you wouldn't have to transform dates from a DB when generating the page).

See also Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

like image 199
Rob Van Dam Avatar answered Oct 20 '22 17:10

Rob Van Dam


Elaborating Rob Van Dam's answer, here is a code sample (using jQuery UI datepicker) for fetching enabled dates using AJAX. I use AJAX to query a PHP page that returns the enabled date from a database (because I only want to show dates where I have actual data).

The idea is to do the AJAX query each time the user change month and then store the enabled dates for this month in a global array (allowedDates) that is later used by beforeShowDay.

Of course, you could do the AJAX query in beforeShowDay, but this would be quite inneficient due to the high number of AJAX queries (more than 30 for each month).

var allowedDates = new Object();

function queryAllowedDates (year, month, id) {
  $.ajax({
    type: 'GET',
    url: 'calendar_days.php',
    dataType: 'json',
    success: function(response) { 
      allowedDates[id] = response.allowedDates;
    },
    data: {year:year,month:month},
    async: false
  });
}

$("#datepicker1").datepicker({
  dateFormat: 'dd.mm.yy', 
  changeMonth: true, 
  changeYear: true ,
  beforeShow: function (input) {
    var currentDate = $(input).datepicker('getDate');
    var id = $(input).attr('id');
    queryAllowedDates(currentDate.getFullYear(), currentDate.getMonth()+1,id);
  },
  onChangeMonthYear: function (year, month, inst) {
    queryAllowedDates(year, month, inst.input.attr('id'));
  },
  beforeShowDay: function (day) {
    var id = $(this).attr('id');

    var date_str = [
      day.getFullYear(),
      day.getMonth() + 1,
      day.getDate()
    ].join('-');

    if (allowedDates[id] != undefined && allowedDates[id][date_str]) {
      return [true, 'good_date', 'This date is selectable'];
    } else {
      return [false, 'bad_date', 'This date is NOT selectable'];
    } 
  }
});

In this example, the PHP page returns a JSON array containing something like :

{"allowedDates":{"2008-12-04":1,"2008-12-11":1}}
like image 29
Julien Avatar answered Oct 20 '22 18:10

Julien