Quote:
Originally Posted by Scubadreams
Hi,
I want to filter and sort my optionlists.
I tried to put the options in a variabel and know it is an object and actually I want it in an array, because as soon it is in an array I can sort and filter it.
- oToSortOptions = document.forms[0].selectId.options;
-
alert( oToSortOptions);
-
The alert let me know I´v got a object, but I want the array.
Other than applying a sort function to the options, the only way I know is to copy the text properties into an array, sort the array, then create a new set of options using the original options to associate the sorted .text properties with the original .value properties.
Finally copy the new options into the select element.
Here are two select sort functions with the same functionality. The first performs a bubblesort, the second (recommended) uses the above algorithm.
-
function selectSort(box)
-
{
-
var didSwap=true, tmp={}, v=box.options,
-
currSelText=(box.selectedIndex==-1?"":box[box.selectedIndex].text);
-
-
while(didSwap)
-
for(var i=0, didSwap=false, len=v.length-1; i<len; i++)
-
if(v[i].text > v[i+1].text)
-
{
-
tmp.opt=v[i];
-
tmp.dis=tmp.opt.disabled;
-
v[i]=new Option(v[i+1].text, v[i+1].value);
-
v[i].disabled=v[i+1].disabled;
-
v[i+1]=new Option(tmp.opt.text, tmp.opt.value);
-
v[i+1].disabled=tmp.dis;
-
didSwap=true;
-
}
-
-
for(var i=0, len=v.length; i<len && v[i].text!=currSelText; i++)
-
;
-
-
if(i<len)
-
box.selectedIndex=i;
-
}
-
-
-
function sortSelect( box ) /*53637269707465726C61746976652E636F6D*/
-
{
-
/* Sorts the options of <select> element 'box' alphabetically
-
* by their .text property. Preserves the selected option and
-
* the .value property and disabled status of each option.
-
*/
-
-
var currSelText=(box.selectedIndex==-1?"":box[box.selectedIndex].text);
-
-
var opts=box.options, textVals=[], newOpts=[], newIndex=-1;
-
-
for(var i=0,len=opts.length; i<len; i++)
-
textVals[i]=opts[i].text;
-
-
textVals.sort();
-
-
for(var i=0, len=opts.length; i<len; i++)
-
{
-
for(var j=0; j<len && opts[j].text!=textVals[i]; j++)
-
;
-
newOpts[i]=new Option(textVals[i], opts[j].value);
-
newOpts[i].disabled=opts[j].disabled;
-
-
if(currSelText==textVals[i])
-
newIndex=i;
-
}
-
-
for(var i=0; i<len; i++)
-
opts[i]=newOpts[i];
-
-
box.selectedIndex=newIndex;
-
}