Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery UI Datepicker, reverse the order of the year in the dropdowns

I have a datepicker with changeyear: true. The 'year' drop down displays the title as 2009, then instead of the next year below the title being 2008, 2007, 2006 and so on it starts at 1999 and counts upwards. I can't seem to find an easy solution to reverse this order?

like image 504
Lance Avatar asked Oct 20 '09 14:10

Lance


3 Answers

I wouldn't recommend editing the original ui.datepicker.js as Cuong suggested because your changes will be lost as soon as you or another developer replaces the file when a new version is released. Remembering what customisations have been made in order to re-apply is not practical. Instead, you can override the existing _generateMonthYearHeader method in your own separate JS like so:

// store original so we can call it inside our overriding method
$.datepicker._generateMonthYearHeader_original = $.datepicker._generateMonthYearHeader;

$.datepicker._generateMonthYearHeader = function(inst, dm, dy, mnd, mxd, s, mn, mns) {
  var header = $($.datepicker._generateMonthYearHeader_original(inst, dm, dy, mnd, mxd, s, mn, mns)),
      years = header.find('.ui-datepicker-year');

  // reverse the years
  years.html(Array.prototype.reverse.apply(years.children()));

  // return our new html
  return $('<div />').append(header).html();
}

I just wrote this for something I'm working on and it does the trick nicely :)

like image 71
jjenzz Avatar answered Nov 08 '22 04:11

jjenzz


I think the best way to hack the plugin without ripping it is assigning a event handler to the year select item.

//Hack for reverting year order
$(document.body).delegate('select.ui-datepicker-year', 'mousedown', function() {
  (function(sel) {
    var el = $(sel);
    var ops = $(el).children().get();
    if ( ops.length > 0 && $(ops).first().val() < $(ops).last().val() ) {
      $(el).empty();
      $(el).html(ops.reverse());
    }
  })(this);
});

This code must work fine! :P

like image 7
Carlos Yslas Avatar answered Nov 08 '22 04:11

Carlos Yslas


There is a "way" to get the year started from the last date:

dateFormat: 'mm/dd/yy',
changeMonth: true, 
changeYear: true,  
yearRange: "-70:", 
maxDate: "-13Y"

Instead if using yearRange as fixed years yearRange: "1900:-13" it's better to use this from bottom up: "-70:", and set the maxDate. Now I get my year select box starting from 2004 and not 1900.

P.S: All the other solutions have been tested. They are very slow, and some don't work so well (especially the old ones - sets current year instead of 2004 for example).

like image 6
Imnotapotato Avatar answered Nov 08 '22 03:11

Imnotapotato