jQuery ui - datepicker prevent refresh onSelect

Pierre de LESPINAY picture Pierre de LESPINAY · May 19, 2011 · Viewed 18.3k times · Source

I'm using jQuery ui Datepicker to display a yearly inline calendar full of "special dates" (with colors). enter image description here This is to allow users to batch special dates by selecting a range and some other details.

$('#calendar').datepicker({
  ...
  , onSelect: function (selectedDate, inst) {
      $('.date_pick').toggleClass('focused');
      if ($('.date_pick.end').hasClass('focused')) {
        $('.date_pick.end').val('');
      }
      # inst.preventDefault() ? <- not a function
      # inst.stopPropagation() ? <- not a function
      # return (false) ? <- calendar refreshes anyway
    }
  ...
});

I'm also using qtip to show the details on each date

My problem is when I click on the calendar, it reloads itself entirely, so I loose my qtips.

I'd prefer not to use live() with qtip because I don't like the behavior.

I'd also prefer that the calendar not refresh each time I click on it (but this does not seem possible anyway) but I would probably no longer be able to highlight my selection anymore.

Do you have a suggestion for my problems ?

Answer

Yozomiri picture Yozomiri · Jun 4, 2011

I was having a similar problem. I was adding custom buttons to the bottom of the datepicker (using $(id).append), but when I would select a date the datepicker would refresh and destroy them.

This is the date selection function for the datepicker in the jquery-ui library:

_selectDate: function(id, dateStr) {
  ...
    if (onSelect)
        onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
  ...
    if (inst.inline)
        this._updateDatepicker(inst);
  ...
},

As you can see, the function first calls the onSelect event, and then calls _updateDatepicker (which is what redraws the form) if inst.inline is true.

This is my workaround to prevent the form from refreshing while maintaining the selection functionality:

$("#cal_id").datepicker({
  onSelect: function(date, inst){

    //This is the important line.
    //Setting this to false prevents the redraw.
    inst.inline = false;

    //The remainder of the function simply preserves the 
    //highlighting functionality without completely redrawing.

    //This removes any existing selection styling.
    $(".ui-datepicker-calendar .ui-datepicker-current-day").removeClass("ui-datepicker-current-day").children().removeClass("ui-state-active");

    //This finds the selected link and styles it accordingly.
    //You can probably change the selectors, depending on your layout.
    $(".ui-datepicker-calendar TBODY A").each(function(){
      if ($(this).text() == inst.selectedDay) {
        $(this).addClass("ui-state-active");
        $(this).parent().addClass("ui-datepicker-current-day");
      }
    });
  }
});