左右兩個多選清單,搭配「添加」與「刪除」按鈕,讓使用者在兩邊搬移選項——這是很多後台「選擇項目」功能的標準樣式。本文提供一份完整可運行的程式碼,並示範如何動態產生左側選項。
<!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=gb2312" />
<title>多選清單移動</title>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// 動態給左邊下拉列表創建選項
$(document).ready(function(){
for(var i=1;i<=5;i++){
$("#fb_list").append("<option value='"+i+"'>公開招標小型機采購00"+i+"</option>");
}
})
// 添加
$(function(){
$("#add").click(function(){
if($("#fb_list option:selected").length>0){
$("#fb_list option:selected").each(function(){
$("#select_list").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option");
$(this).remove();
})
}else{
alert("請選擇要添加的分包!");
}
})
})
// 刪除
$(function(){
$("#delete").click(function(){
if($("#select_list option:selected").length>0){
$("#select_list option:selected").each(function(){
$("#fb_list").append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option");
$(this).remove();
})
}else{
alert("請選擇要刪除的分包!");
}
})
})
</script>
</head>
<body>
<table width="95%" cellpadding="0" align="center" class="listshow" border="1" cellspacing="0">
<tr><td colspan="4" align="center">選擇分包</td></tr>
<tr>
<td width="30%" align="center" height="150">
<select id="fb_list" multiple="multiple" style="width:300px;height:150px;"></select>
</td>
<td align="center" width="5%">
<input type="button" id="add" value="添加>>" /><br/><br/>
<input type="button" id="delete" value="<<刪除" />
</td>
<td width="30%" align="center">
<select id="select_list" multiple="multiple" style="width:300px;height:150px;"></select>
</td>
</tr>
</table>
</body>
</html>
這份程式碼的關鍵在於:先用 $("#fb_list option:selected").length > 0 判斷是否有選中項,若沒有就跳出提示;有的話則遍歷每個選中項,把它的值與文字 append 到對面的清單,再把原選項 remove 掉。實際專案中,左側選項通常會改從資料庫動態讀取後產生,這裡以 for 迴圈模擬。
這套「判斷 → 遍歷 → append → remove」的模式,是處理多選清單雙向搬移的通用解法,稍加調整就能套用到各種選取情境。