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);;
}())