萬盛學電腦網

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

jQuery 實作雙多選下拉框項目移動(左往右、右往左)完整元件

雙列表框(Dual Listbox / Shuttle)是後台管理常見 UI,用於權限分配、角色選擇、標籤管理等。本文提供完整的 jQuery 元件化實作,支援搜尋、排序、鍵盤操作、表單序列化。

HTML 結構

<div class="dual-listbox">
  <div class="list-wrapper">
    <h4>可選項目</h4>
    <input type="search" class="search" placeholder="搜尋..." aria-label="搜尋可選項目">
    <select id="available" multiple size="10"></select>
  </div>
  <div class="actions">
    <button type="button" class="move-right" aria-label="加入選取">></button>
    <button type="button" class="move-left" aria-label="移除選取"><</button>
  </div>
  <div class="list-wrapper">
    <h4>已選項目</h4>
    <input type="search" class="search" placeholder="搜尋..." aria-label="搜尋已選項目">
    <select id="selected" multiple size="10"></select>
  </div>
</div>
<button type="button" id="btn-save">儲存</button>

jQuery 元件化實作

(function($) {
  $.fn.dualListbox = function(options) {
    const opts = $.extend({
      availableData: [],      // [{value, text}, ...]
      selectedData: [],
      searchPlaceholder: '搜尋...',
      onChange: null          // callback(selectedValues)
    }, options);

    return this.each(function() {
      const $container = $(this);
      const $avail = $container.find('#available');
      const $sel = $container.find('#selected');
      const $searchAvail = $container.find('.list-wrapper:first .search');
      const $searchSel = $container.find('.list-wrapper:last .search');

      // 渲染選項
      function render($select, data) {
        $select.empty().append(data.map(item => 
          ``
        ).join(''));
      }

      // 逃逸 HTML
      function escapeHtml(str) {
        return String(str).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
      }

      // 初始化
      render($avail, opts.availableData);
      render($sel, opts.selectedData);

      // 移動選項:右移
      $container.find('.move-right').on('click', () => {
        $avail.find('option:selected').each(function() {
          $sel.append(this); // 直接移動 DOM 節點,保留事件/資料
        });
        triggerChange();
      });

      // 移動選項:左移
      $container.find('.move-left').on('click', () => {
        $sel.find('option:selected').each(function() {
          $avail.append(this);
        });
        triggerChange();
      });

      // 雙擊移動
      $avail.on('dblclick', 'option', function() { $(this).appendTo($sel); triggerChange(); });
      $sel.on('dblclick', 'option', function() { $(this).appendTo($avail); triggerChange(); });

      // 搜尋過濾
      function bindSearch($input, $target) {
        $input.on('input', function() {
          const term = this.value.toLowerCase();
          $target.find('option').each(function() {
            $(this).toggle($(this).text().toLowerCase().includes(term));
          });
        });
      }
      bindSearch($searchAvail, $avail);
      bindSearch($searchSel, $sel);

      // 鍵盤:Enter 移動、Delete 移除
      $container.find('select').on('keydown', function(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          $(this).find('option:selected').each(function() {
            $(this).appendTo(this.id === 'available' ? $sel : $avail);
          });
          triggerChange();
        } else if (e.key === 'Delete' || e.key === 'Backspace') {
          $(this).find('option:selected').each(function() {
            $(this).appendTo(this.id === 'available' ? $avail : $sel);
          });
          triggerChange();
        }
      });

      // 觸發變更回調
      function triggerChange() {
        const selected = $sel.find('option').map(function() { return this.value; }).get();
        if (opts.onChange) opts.onChange(selected);
      }

      // 公開方法
      this.getSelected = () => $sel.find('option').map(function() { return this.value; }).get();
      this.setSelected = vals => {
        vals = Array.isArray(vals) ? vals : [];
        $sel.find('option').each(function() {
          if (!vals.includes(this.value)) $(this).appendTo($avail);
        });
        $avail.find('option').filter(function() {
          return vals.includes(this.value);
        }).each(function() { $(this).appendTo($sel); });
        triggerChange();
      };
    });
  };
})(jQuery);

// 使用範例
$(function() {
  $('#dual-listbox').dualListbox({
    availableData: [
      { value: 1, text: '公開招標小型機採購001' },
      { value: 2, text: '公開招標小型機採購002' },
      { value: 3, text: '公開招標小型機採購003' },
      { value: 4, text: '李四' },
      { value: 5, text: '王五' }
    ],
    selectedData: [
      { value: 4, text: '李四' },
      { value: 5, text: '王五' }
    ],
    onChange: (selected) => console.log('已選:', selected)
  });
});

CSS 關鍵樣式

.dual-listbox { display: flex; gap: 1rem; align-items: flex-start; }
.list-wrapper { flex: 1; display: flex; flex-direction: column; }
.list-wrapper select { flex: 1; min-height: 200px; }
.actions { display: flex; flex-direction: column; gap: 0.5rem; padding-top: 4rem; }
.actions button { width: 40px; height: 40px; border-radius: 4px; background: #007bff; color: #fff; border: none; cursor: pointer; }
.search { margin-bottom: 0.5rem; padding: 0.375rem 0.75rem; border: 1px solid #ccc; border-radius: 4px; }

表單提交序列化

$('#btn-save').on('click', function() {
  const selected = $('#dual-listbox').data('dualListbox').getSelected();
  // 或直接從 select 取值
  // const selected = $('#selected option').map(function() { return this.value; }).get();
  
  $.ajax({
    url: '/api/assign',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({ items: selected }),
    success: () => alert('儲存成功')
  });
});

現代替代庫推薦

  • bootstrap-duallistbox:功能完整、支援 Bootstrap、鍵盤/觸控/搜尋/排序。
  • Select2 + `multiple` + 自訂模板也可實現類似效果。
  • React/Vue 生態:react-dual-listbox、vue-dual-listbox。

自行實作可完全掌控細節,若專案需求標準,引入成熟庫能節省開發與維護成本。

copyright © 萬盛學電腦網 all rights reserved