Thursday, 7 January 2010

Automatically populate a select box with date options 12 months from now

A function to take a select object, clear it out and then populate it with dates from the current month for a year (12 months).

function createDates(){
var mth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

// previous function sets up f.$ as 'getElementById'
var m = f.$("in_month");
var ml = f.$("out_month");

// get the current Month
var currMth = current.getMonth();

// function is called from the two variables below
// an object is passed through, and all variables on the object are referenced through o

var setMonthSelect = function (o){
o.optMthList.options.length = 0
var y = current.getFullYear();

// cycle through 12 and add the 12 months into the array
for (var i=0; i < 12; i++){

//set up the variables that will go into the options - checkVal is the current month and is incremented in the 'if' statement below
var monthVal = o.optMth[o.checkVal] + '-' + y;
var monthText = o.optMth[o.checkVal] + ' ' + (y-2000);

// figure out if it should be the one that's selected (it's easy, the first one is..)
var sel;
i==0?sel=true:sel=false;

// the thing that actually does the work - function is below (and attribution)
AddSelectOption(o.optMthList, monthText, monthVal, sel);

//if the current month is Dec, make it Jan, otherwise add one
if (o.checkVal == 11){
o.checkVal=0
y++;
}else{
o.checkVal++;
}
}
};

// The calls
setMonthSelect({optMth:mth, checkVal:currMth, optMthList:m});
setMonthSelect({optMth:mth, checkVal:currMth, optMthList:ml});
}

// this function stolen from steven harman
function AddSelectOption(selectObj, text, value, isSelected){
if (selectObj != null && selectObj.options != null){
selectObj.options[selectObj.options.length] = new Option(text, value, false, isSelected);
}
}

No comments:

Post a Comment