셀렉트박스 정렬하기

셀렉트 박스를 각 옵션의 텍스트 혹은 value를 기준으로 정렬해주는 함수다.

사용법은 매우 간단해서...
sboxSort(SELECT 객체의 아이디 혹은 객체, valueSort 여부);와 같다.

만약 위 링크의 예제처럼 select 객체의 아이디가 sbox 라고 했을 때...

  1. sboxSort('sbox');
  2. sboxSort(document.getElementById('sbox'));

1, 2 번 방식이 둘 다 사용가능하다. 두번째 전달값은 value 소트를 할 것인지의 여부인데, 기본값은 false 가 된다.

함수를 페이지에 삽입후 버튼등에 onclick 이벤트를 주는 방식으로 사용하면 되겠다.
function sboxSort(boxIdObj, isValuesort)
{
var obj, sArr, oArr, idx, op;

if (typeof boxIdObj == 'string') obj = document.getElementById(boxIdObj);
else obj = boxIdObj;

if (obj.tagName.toLowerCase() != 'select') return false;
if (typeof isValuesort == 'undefined') isValuesort = false;

sArr = new Array(obj.options.length);
oArr = new Array;

for (idx = 0; idx < obj.options.length; idx++)
{
    if (isValuesort) sArr[idx] = obj.options[idx].value;
    else sArr[idx] = obj.options[idx].text;

    oArr[sArr[idx]] = obj.options[idx];
}
sArr.sort();

for (idx in sArr) obj.appendChild(oArr[sArr[idx]]);

}

예제)
[#NOBR_START#]




[#NOBR_END#]

댓글을 남겨주세요

This site uses Akismet to reduce spam. Learn how your comment data is processed.