Reputation: 9442
I have some javascript that generates a large list of <select>
options (<option>
) elements on the fly. And I need to be able to switch between 3 or 4 different generated lists based on the value of another <select>
menu using an "onchange" event.
Is there a way I can store multiple lists of options and then just redirect the select object to the appropriate list as necessary?
Right now, I have to delete all the options and re-add them one at a time. That seems horribly wasteful / time consuming.
Upvotes: 2
Views: 205
Reputation: 65391
DocumentFragments might be what you're looking for.
http://ejohn.org/blog/dom-documentfragments/
Furthermore, various operations -- such as inserting nodes as children of another Node -- may take DocumentFragment objects as arguments; this results in all the child nodes of the DocumentFragment being moved to the child list of this node.
Upvotes: 1
Reputation: 4234
Seems like it's a perfect case for jQuery templates. You can store all data for every case as json. Create a template of <select> element. When user changed some parameter you'll pick a proper json and bind to a template. You can find examples here.
Upvotes: 0
Reputation: 83376
You could store the different lists of options as simple arrays, then do something like this:
function setThisSelect(selectId, optionsArray){
var sel = document.getElementById(selectId);
sel.options.length = 0;
for (var i = 0; i < optionsArray.length; i++)
sel.options.add(optionsArray[i]);
}
And here's how you might create your options:
var optionsArr1 = [];
for (var i = 0; i < 5; i++) {
var op = document.createElement("option");
op.value = i;
op.text = i;
optionsArr1.push(op);
}
Here's a fiddle:
But if you're wanting to do a lot of this, it might get tedious pretty quickly. This might be something a library like jQuery can help accomplish with a lot less code.
Upvotes: 3