JSFiddle - React, Tailwind, and code Playground
HTML
<select id="tdp-0" name="taxo[0][term]">
<option value="august-2014">August 2014</option>
<option value="may-2014">May 2014</option>
<option value="march-2014">March 2014</option>
<option value="december-2013">December 2013</option>
<option value="august-2013">August 2013</option>
</select>
JavaScript
//For adding capitalaizing the first letter-function to strings
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
}
myMonths = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
//Array that hold date objects
dateArray = new Array();
//Create date objects
function getDateObject(value){
montAndYear = value.split("-");
date = new Date();
//Set year and month
date.setYear(montAndYear[1]);
//Since the months are stored by name, get the proper value from the myMoths array
date.setMonth(myMonths.indexOf(montAndYear[0]));
return date;
}
function updateSelection(){
$("#tdp-0")
.find('option')
.remove()
.end();
for(i = 0; i < dateArray.length; i++){
month = myMonths[dateArray[i].getMonth()];
year = dateArray[i].getFullYear();
$("#tdp-0").append('<option value="'+month+'-'+year+'">'+ month.capitalize() + ' ' + year +'</option>');
if(i == 0){
$("#tdp-0").val(month+'-'+year);
}
}
}
//Get all the values and sorts them
$("#tdp-0 option").each(function(){
dateArray.push(getDateObject($(this).val()));
}).promise().done(function(){
dateArray.sort(function(a,b){
return a>b ? -1 : a<b ? 1 : 0;
});
updateSelection();
});