0

I'm trying to call a function which loops out options for two different selects, using parameters to tell the function which array of items it should use. The problem comes when I try to convert the parameter to "plain text" so that I can use it as a property of the calendarModel. If I use dot notation it tries to access a property called category in calendarModel which obviously doesn't work.

After looking at this question: How to create an object property from a variable value in JavaScript? I thought that my solution would work, but the problem in that question isn't exactly like mine so I must've misunderstood it or something.

Right now I only get 1 option and it's undefined. When it really should be as many as items in years and months as well as having the values. Where am I going wrong here?

var calendarModel = {
    months: ['January', 'February', 'March', 'April', 'May', 'June',
         'July', 'August', 'September', 'October', 'November', 'December'
        ],
    years: ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024']
}

(function() {

var selectMonth = document.getElementById('month');
var selectYear = document.getElementById('year');

function createOptions(category, element) {

        for (i = 0; i < calendarModel[category].length; i++) {
            var option = document.createElement('option');
                option.innerHTML = calendarModel[category[i]];
                option.value = option.innerHTML;
                element.appendChild(option);
        }
    }

    createOptions('years', selectYear);
    createOptions('months', selectMonth);;
}())
Community
  • 1
  • 1
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175

2 Answers2

1

You're a bit mixed up. category is just a string, so you're passing in y (years) into calendarModel

I think you want to use the loop index on the outside.

option.innerHTML = calendarModel[category][i]; //notice [i] is not the index of the category string anymore
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0

If you take a look at the following line:

option.innerHTML = calendarModel[category[i]];

This is going to try and look for property i on category, which is just a string. This is why you are getting undefined.

Instead, you should be doing the following:

option.innerHTML = calendarModel[category][i];

This will find the corresponding values to your category property on calendarModel

justinpinili
  • 894
  • 6
  • 13
  • Ye I fixed that, but I still only get one option because it can't find a length of calendarModel[category]. Do I need to add brackets there or something? – Chrillewoodz Nov 26 '14 at 20:02
  • nvm found the problem, there was a left over z-index in my css that prevented me from seeing the rest.. – Chrillewoodz Nov 26 '14 at 22:37