views:

47

answers:

1

I have a javascript array of dates, in the form

{year:'2010',month:'6',day:'23'}

I need to have three <select>s in a row, the first populated with the years in the list, the second populated with the months in the year selected by the first, and the third populated with the days corresponding to the selected year and month.

I do not have access to libraries like jQuery.

What is the best way to handle this?

+1  A: 

To retrieve the year data to setup the initial select, you'll have to traverse the array at least once (hopefully only once).

Due to the fact you want the second select populated in response to the first and the third populated based on the second and first, you'll need a fast way to reference them.

I'd initially populate the select, whilst sorting out the data into an easier to retrieve system. I'm using Arrays with keys here, others may suggest it is better to use Objects with keys instead.

/* Global variables */
var arr = new Array({year:'2010',month:'6',day:'23'},
                    {year:'2011',month:'6',day:'23'},
                    {year:'2010',month:'5',day:'23'});
var srt = new Array();

function populateArrs()
{
for(var i=0;i<arr.length;i++)
{
  var y = arr[i].year;
  var m = arr[i].month;
  var d = arr[i].day;
  var in_select = false;

  /* Month array, day array */
  var mArr;
  var dArr;

  if(srt[y] != null)
  {
    mArr = srt[y];
    in_select = true;
  }
  else
    mArr = new Array();


  if(mArr[m] != null)
    dArr = mArr[m];
  else
    dArr = new Array();

  if(dArr[d] == null)
    dArr[d] = d;
  /* No else as at this stage it will already exist in array set */

  mArr[m] = dArr;
  srt[y] = mArr;

  /* Don't duplicate values in the select */
  if(!in_select) 
  {
    var opt = document.createElement('option');
    opt.value = y;
    opt.text = y;
    /* Get your year select */
    var ySel = document.getElementById('year_select'); 
    ySel.appendChild(opt);
  }
}
}

if (window.addEventListener)
  window.addEventListener("load", populateArrs, false);
else if (window.attachEvent)
  window.attachEvent("onload", populateArrs);

Afterwards, you need to set up onclick events to populate your other selects dynamically. You can simply reference the appropriate arrays by using lookups and for..in loops.

Months:

var ySel = document.getElementById('year_select');
var mArr = srt[ySel.options[ySel.selectedIndex].value];
for( x IN mArr)
  /* Populate month select */

Days:

/*As above, then */
var mSel = document.getElementById('month_select');
var dArr = srt[mSel.options[mSel.selectedIndex].value];

Hope that helps.

staticbeast