<table class="listshow">
<tr>
<td><select multiple id="fb_list" size="8"></select></td>
<td class="actions">
<button type="button" id="add">></button><br>
<button type="button" id="addAll">>></button><br>
<button type="button" id="remove"><</button><br>
<button type="button" id="removeAll"><<</button>
</td>
<td><select multiple id="select_list" size="8"></select></td>
</tr>
</table>
$(function() {
for (var i = 1; i <= 5; i++) {
$('#fb_list').append('');
}
});
$(function() {
// 選中 → 右
$('#add').on('click', function() {
moveSelected('#fb_list', '#select_list', '請選擇要添加的分包!');
});
// 全部 → 右
$('#addAll').on('click', function() {
moveAll('#fb_list', '#select_list');
});
// 選中 ← 左
$('#remove').on('click', function() {
moveSelected('#select_list', '#fb_list', '請選擇要刪除的分包!');
});
// 全部 ← 左
$('#removeAll').on('click', function() {
moveAll('#select_list', '#fb_list');
});
});
function moveSelected(fromSel, toSel, emptyMsg) {
var $opts = $(fromSel + ' option:selected');
if (!$opts.length) return alert(emptyMsg);
$opts.appendTo(toSel);
}
function moveAll(fromSel, toSel) {
$(fromSel + ' option').appendTo(toSel);
}
.appendTo() 同時實現「移除+新增」jQuery 的 appendTo 會將匹配元素從原位置**移動**到目標容器,無需手動 .remove() 再 .append(),程式碼極度精簡。
sortSelect('#select_list') 依文字或 value 排序。<select> 上方加 <input type="search">,keyup 時過濾 <option> 顯示/隱藏。leftItems[]/rightItems[],操作陣列後 render() 重建選項,確保狀態一致性。