雙向穿梭列表框(左側候選、右側已選)是很常見的表單互動。以下把常用操作整理成一組可重複使用的小函式。
<script language="javascript">
/* 列表框互相操作函數集 */
// 描述:添加不重複的列表框元素
function selAdd(srcList, dstList) {
var selectedIndex = new Array();
var count = 0;
for (i = 0; i < srcList.options.length; i++) {
if (srcList.options[i].selected) {
selectedIndex[count] = i;
count++;
}
}
for (j = 0; j < selectedIndex.length; j++) {
k = selectedIndex[j];
// 只有目標清單中不存在時才加入,避免重複
if (chkDup(srcList.options[k].value, dstList) == false) {
dstList.options.length++;
var len = dstList.options.length - 1;
dstList.options[len].value = srcList.options[k].value;
dstList.options[len].text = srcList.options[k].text;
}
}
}
// 描述:刪除列表框元素
function selDel(list) {
var len = list.options.length;
var idx = 0;
// 邊刪邊走,刪掉後索引不變,否則會跳過相鄰項
while (idx < len) {
if (list.options[idx].selected) {
list.options.remove(idx);
len = list.options.length;
} else {
idx++;
}
}
}
// 描述:檢測列表框元素是否重複
function chkDup(item, list) {
for (i = 0; i < list.options.length; i++) {
if (item == list.options[i].value) {
return true;
}
}
return false;
}
// 描述:選取列表框的全部成員,並把值串接寫入指定欄位
function selSel(list, item) {
item.value = " ";
for (i = 0; i < list.options.length; i++) {
list.options[i].selected = true;
item.value += list.options[i].value + " ";
}
}
// 描述:依值單選一項
function selSelSingle(list, value) {
for (i = 0; i < list.options.length; i++) {
if (list.options[i].value == value) {
list.options[i].selected = true;
break;
}
}
}
// 描述:根據陣列初始化列表框
function selList(item, arr) {
var curIndex, insIndex, val, text;
var arrItem = new Array();
if (item) {
item.length = 0;
curIndex = 0;
for (i = 0; i < arr.length; i++) {
item.length++;
insIndex = item.length - 1;
if (arr[i]) {
// 約定格式為 "value, text"
arrItem = arr[i].split(", ");
text = arrItem[1];
val = arrItem[0];
item.options[insIndex].text = text;
item.options[insIndex].value = val;
}
}
}
}
</script>
幾個實作上的重點:selAdd 透過 chkDup 過濾重複項,避免同一筆資料被加入兩次;selDel 採 while 迴圈而非 for,因為刪除元素會讓索引位移,用 for 搭配遞增索引很容易漏刪;selList 則約定以「值, 文字」的字串格式傳入,再切分成 value 與 text 兩部分。