How can you unobtrusively increase the jQuery Datepicker class?

You can pass special strings to the setDate () method of the jQuery Datepicker class of type "+7", which will be translated into "7 days from today":

http://docs.jquery.com/UI/Datepicker#method-setDate

But you cannot get this "+7" back. When you call getDate (), you get the estimated total date.

I have a use case where I need to pull out a special line "+7" for distribution. One piece of code passes a special string to Datepicker and passes the Datepicker to another piece of code that pulls out the date, but the latter sometimes needs to know a special string, not the estimated date.

Therefore, I need to improve the Datepicker tool to (a) save the special code inside and (b) expose it using the getOriginallyPassedInDate () method or some of them.

I am not a jQuery / Javascript ninja, so I could use some recommendations on how I could preferably - unobtrusively add the necessary functionality to the Datepicker class, how you can defuse an object in Ruby. I guess,.

+5
source share
3 answers

this works based on the @petersendidit suggestion:

// http://paulirish.com/2010/duck-punching-with-jquery/
(function($){
  var _raw = null;
  var _old = $.fn.datepicker;
  $.fn.datepicker = function(arg1, arg2){
    if('getRawDate'==arg1){
      return _raw;
    } else {
      if('setDate'==arg1){
        _raw = arg2;
      }
      return _old.apply(this, arguments);
    }
  };
})(jQuery);
+2
source

Duck Punch Monkey Patch.

jQuery UI v1.8rc3, defaultDate, setDate, . onSelect onClose fn, :

    $('.pick-date').datepicker({
        showWeek: true,
        weekHeader: 'W#',
        defaultDate: "+9",
        onSelect: function(dateText, inst) {
            alert("Select: inst.defaultDate = " + inst.settings.defaultDate);
        },
        onClose: function(dateText, inst) {
            alert("Close: inst.defaultDate = " + inst.settings.defaultDate);
        }
    });

In the Teach-a-man-to-fish department, I did 2 things to find out:

  • I looked at the source code for datepicker. It clearly shows the defaultDate parameter, which is documented to accept +/- N for an offset. It has no option setDate.

  • I launched the page in the debugger and placed a gap inside the function onClose. There I was able to expand the inst parameter and saw that the settings were saved there.

+1
source

All Articles