JQuery UI Datepicker: Reverse Order of Year Range

Adding a Date Of Birth field to a form using datepicker, i was surprised that although there are options to set yearRange, min/max Date etc, there isn’t an option to set the order the years appeared in the dropdown.

After Googling I found a solution on the jQuery forum, adding a reverseYearRange option to the datepicker code, although as it was posted 2 years ago this solution no longer works with the latest jQueryUI version.

Below is the modified version of Xela’s code I added to the jQuery UI Javascript file to enable the reverseYearRange option.

First set the variable underneath the yearRange declaration:

yearRange: 'c-10:c+10',
// Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) reverseYearRange: false,
// true to display range of years in reverse order in drop-down

Next find the following code in the _generateMonthYearHeader method:

for (; year <= endYear; year++) {
inst.yearshtml += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}

and replace it with this:

var reverseYearRange = this._get(inst, 'reverseYearRange');
if(reverseYearRange){
for (; year <= endYear; endYear--) {
inst.yearshtml += '<option value="' + endYear + '"' +
(endYear == drawYear ? ' selected="selected"' : '') +
'>' + endYear + '</option>';

}
}else{
for (; year <= endYear; year++) {
inst.yearshtml += ‘<option value=”‘ + year + ‘”‘ +
(year == drawYear ? ‘ selected=”selected”‘ : ”) +
‘>’ + year + ‘</option>’;

}
}

Then you simply add ‘reverseYearRange’ as an option when implementing the datepicker:


yearRange: "-70:-14",
reverseYearRange: true

Leave a Reply

Your email address will not be published. Required fields are marked *