「左邊是候選清單、右邊是已選清單」這種雙欄穿梭介面,常見於權限配置、群組管理與多選排序。核心邏輯其實只有一件事:把選中的 option 從一邊搬到另一邊。以下用原生 JavaScript 完整實作。
走訪來源清單的所有 option,逐一檢查是否被選中;是的話就塞進目標清單,再從來源移除,並把索引減一以修正迴圈位置。
function copyToList(from, to){
var fromList = document.forms[0][from];
var toList = document.forms[0][to];
// 若目標清單只有提示用的 temp 選項,先清掉
if (toList.options.length > 0 && toList.options[0].value == 'temp') {
toList.options.length = 0;
}
var sel = false;
for (var i = 0; i < fromList.options.length; i++) {
var current = fromList.options[i];
if (current.selected) {
sel = true;
if (current.value == 'temp') {
alert('不能選擇這個項目!');
return;
}
toList.options[toList.length] = new Option(current.text, current.value);
fromList.options[i] = null; // 從來源移除
i--; // 索引回退,避免漏掉相鄰項
}
}
if (!sel) alert('你還沒有選擇任何項目!');
}
這裡有兩個關鍵細節:i-- 是為了抵消陣列收縮造成的位移,否則連續選兩項時會漏掉一項;而 temp 提示項的處理則讓「請先從左邊選擇」這類引導文字不會被誤搬到右邊。
多選 select 在表單提交時,只會送出被選中的選項。所以按下送出鈕前,必須把右邊清單全部標成 selected:
function allSelect(){
var chsen = document.getElementById('chosen');
if (chsen.length && chsen.options[0].value == "temp") return;
for (var i = 0; i < chsen.length; i++) {
chsen.options[i].selected = true;
}
}
若不想依賴 select 的序列化行為,另一個常見做法是同步把值寫進隱藏欄位:
function getdata() {
var List = document.forms[0].RoleList;
var roles = document.getElementById("TRoleList");
roles.value = "";
var s = "";
if (List.length != 0) {
for (var i = 0; i < List.length; i++) {
s += List.options[i].value + ",";
}
}
roles.value = s;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>雙 select 穿梭選單</title>
<!-- 此處放入上述 copyToList、allSelect、getdata -->
</head>
<body>
<table border="0">
<form onSubmit="allSelect()">
<tr>
<td>
<select name="possible" size="4" MULTIPLE style="width:200px">
<option value="1">中國廣州</option>
<option value="2">中國上海</option>
<option value="3">中國北京</option>
<option value="4">中國武漢</option>
</select>
</td>
<td>
<a href="javascript:copyToList('possible','chosen')">添加至右方 --><br><br></a>
<a href="javascript:copyToList('chosen','possible')"><-- 添加至左方</a>
</td>
<td>
<select name="chosen" id="chosen" size="4" MULTIPLE style="width:200px">
<option value="temp">從左邊選擇你的地區</option>
</select>
</td>
</tr>
</form>
</table>
<input type="button" value="提交" onclick="allSelect()" />
<input type="text" style="display:none;" id="TRoleList">
</body>
</html>
實務上通常還會加上:全選/取消全選按鈕、雙擊 option 直接搬移、搬移後依 value 排序,以及重新選取時還原提示項。另外提醒一個可讀性問題:原範例用 eval('document.forms[0].'+from) 來動態取元素,這是不必要的風險,改用 document.forms[0][from] 或 document.getElementsByName(from)[0] 即可達到相同效果,也不必付出具名 eval 的代價。