Friday, March 30, 2007

Javascript-Sorting Dates in List Box

<html>
<head>
<title>Javascript-Sorting Dates in List Box</title>
<script language="JavaScript">
function Sort_Dates() {
var x, y, holder;
var list_box = document.frm.list_dates;

FirstDate = new Date();
SecondDate = new Date();

for(x = 0; x < list_box.options.length; x++)
{
for(y = 0; y < (list_box.options.length-1); y++)
{
array_first = list_box.options[y].value.split("/");
array_second = list_box.options[y+1].value.split("/");

FirstDate.setMonth(array_first[0]);
FirstDate.setDate(array_first[1]);
FirstDate.setYear(array_first[2]);

SecondDate.setMonth(array_second[0]);
SecondDate.setDate(array_second[1]);
SecondDate.setYear(array_second[2]);

if (FirstDate >SecondDate) //here you can modify the condition to work for ascending or descending
{
holder = list_box.options[y+1].value;
list_box.options[y+1].value = list_box.options[y].value;
list_box.options[y+1].text = list_box.options[y].value;
list_box.options[y].value = holder;
list_box.options[y].text = holder;
}
}
}

}
</script>
</head>
<body>
<form name="frm">
<select name="list_dates" id="list_dates" multiple size="10">
<option value="3/31/2007">3/31/2007</option>
<option value="2/15/2007">2/15/2007</option>
<option value="3/25/2007">3/25/2007</option>
<option value="2/6/2007">2/6/2007</option>
</select>
<input type="button" value="Sort Dates" onClick="Sort_Dates();">
</form>
</body>
</html>


Disclaimer: Any code or advice given is for instructional purposes only. We will not be responsible for any loss or damage caused by using this script.

No comments: