so_createDateDropDown

Summary

Returns a <select> element object with dates from the current date either into the past or the future based on the value of the direction argument.

Arguments:

Integer numDays
The number of days from today to include in the select element.
Integer direction
Determines if days are counted forward of backward. 0 for forward, 1 for backwards.

Usage:

// create a select element with dates up to ten days in the future
var dateSelectObject = so_createDateDropDown(10,0);

Caveat

In the spirit of unobtrusive scripting and progressive enhancement, it is recommended that you provide a fallback means to this element should the user not have javascript available. A simple example would be a hard coded text input that the user can type their data in which would be replaced by this dynamically created element.

Example:

The returned select object has been appended to the following form:

document.getElementsByTagName("form")[0].appendChild(so_createDateDropDown(10,0));

Code

function so_createDateDropDown(numDays,direction) {
	var current = Date.parse(new Date());
	var dayLength = 86400000;
	var maxDate = direction?current - (dayLength*numDays):current + (dayLength*numDays);
	maxDate = new Date(maxDate);
	months = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

	dSelect = document.createElement("select");
	dSelect.setAttribute("name","dateDropDown");
	
	do {
		current+=direction?-dayLength:dayLength;
		prvDateObj = new Date(current);
		vDate = prvDateObj.getFullYear() + "" + prvDateObj.getMonth() + "" + prvDateObj.getDate();
		dOption = document.createElement("option");
		dOption.setAttribute("value",vDate);
		dOption.appendChild(document.createTextNode(days[prvDateObj.getDay()] + ", " + months[prvDateObj.getMonth()] + " " + prvDateObj.getDate() + " " + prvDateObj.getFullYear()));
		dSelect.appendChild(dOption);
		condition = direction?prvDateObj>maxDate:prvDateObj<maxDate;
	} while(condition);

	return dSelect;
}

License

This code is issued under a Creative Commons license. You do not need my permission to use it, though I'm always interested in seeing where my code has ended up if you want to drop me a line.

slayeroffice main