|
I am trying to select all the elements in a Listbox/SelectBox.
At the moment I am using the following function *which is working*, the only thing is it takes around 10 seconds to select all elements(of which there are 652).
I'm a beginner at javascript so I was wondering whether anyone knew of a faster way to select all elements.
<script>
function selectAll(selectBox, selectAll, ensureOneSelected) {
var selectBoxElement = null;
var selectBoxOption = null;
var boolSelect = selectAll;
if (typeof selectBox == "string") {
selectBoxElement = document.getElementById(selectBox);
selectBoxOption = selectBoxElement.options;
}
if (selectBoxElement.type == "select-multiple") {
var max = (selectBoxOption.length);
var modMaxUnrollFactor = (max % 4);
max -= modMaxUnrollFactor ;
for(var i = 0; i < max; i+=4){
selectBoxOption[i].selected = boolSelect;
selectBoxOption[i + 1].selected = boolSelect;
selectBoxOption[i + 2].selected = boolSelect;
selectBoxOption[i + 3].selected = boolSelect;
}
for (var i = max; i < selectBoxOption.length; i++) {
selectBoxOption[i].selected = boolSelect;
}
if (typeof ensureOneSelected == "boolean") {
if(selectBoxOption[0].selected == false)
{
selectBoxOption[0].selected = ensureOneSelected;
}
}
}
}
</script>
thanks in advance
|
|
|
|
|
What is with the unroll factor and two loops? That is pointless ... running a for loop 600 times isn't what's slow.
Manipulating the DOM can be slow. You might do better to get .innerHTML, do a regex replace for '<option( selected)?' with either '<option' or '<option selected', and then reassign .innerHTML.
|
|
|
|
|
BobJanova wrote: Manipulating the DOM can be slow. You might do better to get .innerHTML, do a
regex replace for '<option( selected)?' with either '<option' or
'<option selected', and then reassign .innerHTML.
Thanks, I'll look into it.
BobJanova wrote: What is with the unroll factor and two loops? That is pointless ... running a
for loop 600 times isn't what's slow.
I'm a c/c++ programmer predominately, force of habit
|
|
|
|
|
Developed a working solution on IE8 though I did run into a select option truncate bug where the first option in innerHTML is removed.
But in the end I developed a workaround for this bug and have a working hack solution which is much much faster, so all is good.
cheers.
|
|
|
|