Reputation: 1451
I want to append multiple options in html select.
Currently I'm using the below code in a loop, but it make the working slow as it have to add new option every time.
Code Snippet:
s.options[s.options.length]= new Option(url, '1');
So I guess, if I can add all the options at once and not one by one like above, maybe it can make it little faster.
Please suggest a more fast function then this one. Thanks
Upvotes: 1
Views: 3036
Reputation: 324567
You may be able to do it with a DocumentFragment
but I'm unsure about browser support. It certainly works in current versions of all browsers (including IE 10) but I doubt it works in old IE.
var frag = document.createDocumentFragment();
for (var i = 0; i < 10; ++i) {
var option = document.createElement("option");
option.value = "" + i;
option.text = "Option " + i;
frag.appendChild(option);
}
s.appendChild(frag);
Demo: http://jsfiddle.net/QsNpe/
Upvotes: 1
Reputation: 17576
try this
var dataArr = [{'value':'val1','text':'text1'},
{'value':'val2','text':'text2'},
{'value':'val3','text':'text3'},
{'value':'val4','text':'text4'},
{'value':'val5','text':'text5'},
{'value':'val6','text':'text6'},
{'value':'val7','text':'text7'}];
// Removes all options for the select box
$('#optExample option').remove();
// .each loops through the array
$.each(dataArr, function(i){
$('#optExample').append($("<option></option>")
.attr("value",dataArr[i]['value'])
.text(dataArr[i]['text']));
});
Upvotes: 0
Reputation: 1754
Try this,
s.options[s.options.length]=function Option(url,'1') { // statements go here };
Upvotes: 1
Reputation: 2245
Try this:
var tmpOptions = [];
for(var i=0; i<optionsLength; i++) {
tmpOptions[i] = new Option(url, i);
}
s.options = tmpOptions;
Upvotes: 0