在多選情境中,常見「左側待選、右側已選」的雙欄選單設計,使用者可以將項目在兩邊移動,甚至調整順序。本文示範如何以JavaScript實作這種下拉選單左右移動的效果。
完整程式碼如下:
<form method="post" name="myform">
<table border="0" width="300">
<tr>
<td width="40%">
<select style="WIDTH:100%" multiple name="list1" size="12" ondblclick="moveOption(document.myform.list1, document.myform.list2)">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="山東">山東</option>
<option value="廣東">廣東</option>
</select>
</td>
<td width="20%" align="center">
<input type="button" value="添加" onclick="moveOption(document.myform.list1, document.myform.list2)"><br/><br/>
<input type="button" value="刪除" onclick="moveOption(document.myform.list2, document.myform.list1)">
</td>
<td width="40%">
<select style="WIDTH:100%" multiple name="list2" size="12" ondblclick="moveOption(document.myform.list2, document.myform.list1)">
</select>
</td>
<td>
<button onclick="changepos(list2,-1)" type="button">上移</button><br/>
<button onclick="changepos(list2,1)" type="button">下移</button>
</td>
</tr>
</table>
值:<input type="text" name="city" size="40">
</form>
<script language="JavaScript">
function moveOption(e1, e2){
try{
for(var i=0;i<e1.options.length;i++){
if(e1.options[i].selected){
var e = e1.options[i];
e2.options.add(new Option(e.text, e.value));
e1.remove(i);
i = i-1;
}
}
document.myform.city.value = getvalue(document.myform.list2);
}catch(e){}
}
function getvalue(geto){
var allvalue = "";
for(var i=0;i<geto.options.length;i++){
allvalue += geto.options[i].value + ",";
}
return allvalue;
}
function changepos(obj,index) {
if(index == -1){
if (obj.selectedIndex > 0){
obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex-1))
}
} else if(index == 1){
if (obj.selectedIndex < obj.options.length-1){
obj.options(obj.selectedIndex).swapNode(obj.options(obj.selectedIndex+1))
}
}
}
</script>
・左右移動:moveOption 函式遍歷來源選單,把被選中的項目加入目標選單並從來源移除,支援點擊按鈕或在項目上雙擊操作。
・上下移:changepos 函式透過 swapNode 交換相鄰項目,達到調整順序的效果。
・同步顯示:每次移動後都呼叫 getvalue 把右側選單的值串接顯示於文字框,方便確認目前所選。按住shift或ctrl即可多選,操作相當直覺。