James Dickens James Dickens - 5 months ago 12
Javascript Question

Populating HTML select drop down with Javascript Copying Pointers

I have the following code where I want 25 identical "SectorList" Drop downs contained in an array SectorNames with 25 elements each accessed by their respective id's of the form "Sector1_1", "Sector1_2" .. etc. all the way to "Sector5_5" .

In the second snippet after filling one drop down I assign the other 24 drop downs to that one. Will this code work and will it have negative consequences for when I want to access each Sector Drop Down with their Id's later. It seems that this is a much simpler way then running the loop in the second snippet for each drop down since GlobalEntry[5] has thousands of entries.



// first code snippet
var SectorNames = new Array(25);
var SectorString = "SectorList";
for (var i = 0; i < 5; j++) {
for (var j = 0; i < 5; i++) {
SectorString = SectorString + String(i) + "_" + String(j);
SectorNames[i*5 + j] = document.getElementById(SectorString);
}
}

//second code snippet
for (var i = 0; i < GlobalObject[5].length; i++) {
var opt = GlobalObject[5][i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
SectorNames[0].options.add(el);
}

for (var j = 1; j < SectorNames.length; j++) {
SectorNames[j] = SectorNames[0];
}




Answer

Assigning to sectorNames[j] doesn't change the DOM element, it just changes the Javascript variable. If you want to fill in the options of the <select> element, assign to its innerHTML.

var optionHTML = SectorNames[0].innerHTML;
for (var j = 1; j < SectorNames.length; j++) {
    SectorNames[j].innerHTML = optionHTML;
}