萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 多選框左右移動選項完整實作:單項/全量雙向遷移

介面結構

<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() 重建選項,確保狀態一致性。
copyright © 萬盛學電腦網 all rights reserved