I’m creating a javascript method that populates lists depending on a radio button selected previously. As it depends on animals or plants to populate it, my problem comes when I have to populate it after it’s already been populated. I mean, the plants dropdownlist has 88 elements, and the animals is 888, when I try to come back from animals to plants, I get some of the animals. I know that my controller method is working properly because it returns the values I select, so the problem is the javascript method. Here is the code:
if(selector == "sOrder")
alert(document.getElementById(selector).options.length);
for (i = 0; i < document.getElementById(selector).options.length; i++) {
document.getElementById(selector).remove(i);
}
if (selector == "sOrder")
alert(document.getElementById(selector).options.length);
document.getElementById(selector).options[0] = new Option("-select-", "0", true, true);
for (i = 1; i <= data.length; i++) {
document.getElementById(selector).options[i] = new Option(data[i - 1].taxName, data[i - 1].taxRecID);}
Here is the strange thing, when I enter the method I try to erase all the elements of the dropdownlist in order to populate it afterwards. As sOrder is the same selector I had previously selected, I get the elements, the thing is that the first alert I get the proper result, 888, but in the second alert, I should get a 0 right? It shows 444, so when I populate it again it just overrides the first 88 plants and then animals till 444. What am I doing wrong?
Thank you all in advance,
Victor
Essentially you are removing from beginning to the end of the list by using the index, but as you do the index of each consecutive item gets decreased. If you remove from the end to the beginning, the indexes remain the same and you can remove them by index.
Replace
With
A simpler way of removing all items from a select box might be to use:
This would yank the html inside the select. (note I’ve only tested this in Firefox 3.6.2 but believe this should work in most modern browsers)