I want this javascript to create options from 12 to 100 in a select with id="mainSelect", because I do not want to create all of the option tags manually. Can you give me some pointers? Thanks
function selectOptionCreate() {
var age = 88;
line = "";
for (var i = 0; i < 90; i++) {
line += "<option>";
line += age + i;
line += "</option>";
}
return line;
}
The one thing I'd avoid is doing DOM operations in a loop to avoid repeated re-renderings of the page.
Edit: removed the function to show how you can just assign the html you've built up to another select element - thus avoiding the unnecessary looping by repeating the function call.
You could achieve this with a simple
for
loop:JS Fiddle demo.
JS Perf comparison of both mine and Sime Vidas' answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.
Edited in response to comment from OP:
JS Fiddle demo.
And, finally (after quite a delay...), an approach extending the prototype of the
HTMLSelectElement
in order to chain thepopulate()
function, as a method, to the DOM node:JS Fiddle demo.
References:
node.appendChild()
.document.getElementById()
.element.innerHTML
.Often you have an array of related records, I find it easy and fairly declarative to fill
select
this way:This will replace existing options.
You can use
selectEl.insertAdjacentHTML('afterbegin', str);
to add them to the top instead.And
selectEl.insertAdjacentHTML('beforeend', str);
to add them to the bottom of the list.IE11 compatible syntax:
See: What is the best way to add options to a select from an array with jQuery?
I don't recommend doing DOM manipulations inside a loop -- that can get expensive in large datasets. Instead, I would do something like this:
You can read more about DocumentFragment on MDN, but here's the gist of it:
Here you go:
Live demo: http://jsfiddle.net/mwPb5/
Update: Since you want to reuse this code, here's the function for it:
Usage:
Live demo: http://jsfiddle.net/mwPb5/1/