「左邊是候選清單、右邊是已選清單,中間兩個箭頭可以搬來搬去」——這種穿梭框(transfer)在授權、分發、標籤選擇等場景非常常見。核心其實只有一個 while 迴圈。
<table width="380" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="150">
<table width="150" border="0" cellpadding="1" cellspacing="1" bgcolor="#CAFAFC">
<tr>
<td height="25" bgcolor="#FFFFFF"> 請選擇:</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">
<select name="sel_place1" size="6" multiple id="sel_place1" style="width:100px">
<option value="sel1">江蘇省</option>
<option value="sel2">廣東省</option>
<option value="sel3">河南省</option>
<option value="sel4">吉林省</option>
<option value="sel5">浙江省</option>
</select>
</td>
</tr>
</table>
</td>
<td width="80" align="center" valign="bottom">
<input name="sure1" type="button" id="sure1"
onClick="allsel(document.form1.sel_place2, document.form1.sel_place1);"
value="<<">
<input name="sure2" type="button" id="sure2"
onClick="allsel(document.form1.sel_place1, document.form1.sel_place2);"
value=">>">
</td>
<td width="150">
<table width="150" border="0" cellpadding="1" cellspacing="1" bgcolor="#CAFAFC">
<tr><td height="25" bgcolor="#FFFFFF"> 請選擇:</td></tr>
<tr>
<td align="center" bgcolor="#FFFFFF">
<select name="sel_place2" size="6" multiple id="sel_place2" style="width:100px">
</select>
</td>
</tr>
</table>
</td>
</tr>
</table>
兩個 select 都必須有 multiple 才能多選,size="6" 則控制同時顯示幾列。中間兩顆按鈕的 onclick 呼叫同一個函式,只是把來源與目標的順序對調——這是整份程式最漂亮的地方。
function allsel(n1, n2) {
while(n1.selectedIndex != -1) {
var indx = n1.selectedIndex;
var t = n1.options[indx].text;
n2.options.add(new Option(t));
n1.remove(indx);
}
}
三個 API 各司其職:
select.selectedIndex 回傳第一個被選中選項的索引,若無任何選中則為 -1。這正好構成 while 迴圈的終止條件。new Option(text) 建立一個新的 option 物件,options.add() 把它掛進目標 select。select.remove(index) 把來源中的該項刪掉。因為每次迴圈都會移除一個選項,selectedIndex 就會自動指向下一個被選中的項,迴圈得以持續推進,直到再也沒有選中項(回傳 -1)為止。這個「搬完就刪、刪完自動補位」的設計,比用 for 迴圈加索引管理簡潔許多。
用標準 DOM API 重寫,語意會更清楚,也不必依賴 selectedIndex 只取第一個的特性:
function moveAll(from, to) {
[...from.options]
.filter(o => o.selected)
.forEach(o => to.add(new Option(o.text, o.value, o.selected, o.selected)));
[...from.options]
.filter(o => o.selected)
.forEach(o => from.remove(o.index));
}
document.querySelector("#btnRight")
.addEventListener("click", () => moveAll(sel1, sel2));
document.querySelector("#btnLeft")
.addEventListener("click", () => moveAll(sel2, sel1));
若要搬移「單一選中項」而非全部,把 while 換成 if 即可;若要支援雙向拖放或搜尋過濾,穿梭框通常就該改用专门的 UI 元件了。
這個範例有個明顯缺陷:搬移後只存在前端 DOM 中,表單送出時並未同步把值寫進 hidden 欄位,後端收不到使用者搬過去的結果。實作時記得在提交前把目標 select 的所有 option 值收集起來,塞進一個 <input type="hidden">(多個值就準備多個同 name 的 hidden 欄位),否則這個元件只是好看而已。