萬盛學電腦網

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

JavaScript 雙 Select 多選選項雙向移動完整實作 (含全選、表單提交)

功能需求

  • 兩個 <select multiple> 並排
  • 中間按鈕:選項雙向移動 (→ 添加至右、← 添加至左)
  • 右側預設提示項目「請從左側選擇」
  • 表單提交前自動全選右側所有項目
  • 隱藏欄位收集右側所有值以便後端接收

完整可執行代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>雙 Select 選項移動示範</title>
    <style>
        .container { display:flex; align-items:center; gap:10px; font-family:sans-serif; }
        select { width:200px; height:150px; border:1px solid #ccc; border-radius:4px; }
        .btn-group { display:flex; flex-direction:column; gap:8px; }
        .btn-group a { text-decoration:none; color:#0066cc; font-size:14px; }
        .btn-group a:hover { text-decoration:underline; }
        #hiddenValues { width:300px; margin-top:10px; font-family:monospace; font-size:12px; }
    </style>
</head>
<body>
    <form id="myForm" onsubmit="return prepareSubmit()">
        <div class="container">
            <select id="leftSelect" name="leftSelect" multiple>
                <option value="1">中國廣州</option>
                <option value="2">中國上海</option>
                <option value="3">中國北京</option>
                <option value="4">中國武漢</option>
            </select>

            <div class="btn-group">
                <a href="javascript:void(0);" onclick="moveOptions('leftSelect', 'rightSelect')">添加至右方 →</a>
                <a href="javascript:void(0);" onclick="moveOptions('rightSelect', 'leftSelect')">← 添加至左方</a>
            </div>

            <select id="rightSelect" name="rightSelect" multiple>
                <option value="temp" disabled>請從左側選擇您的地區</option>
            </select>
        </div>

        <input type="hidden" id="hiddenValues" name="selectedRegions">
        <br>
        <button type="submit">提交表單</button>
        <button type="button" onclick="collectValues()">預覽隱藏欄位值</button>
    </form>

    <script>
        // 核心移動函數
        function moveOptions(fromId, toId) {
            var fromSel = document.getElementById(fromId);
            var toSel = document.getElementById(toId);
            var moved = false;

            // 移除右側提示項
            if (toId === 'rightSelect' && toSel.options.length > 0 && toSel.options[0].value === 'temp') {
                toSel.remove(0);
            }

            // 從後往前遍歷,避免索引錯亂
            for (var i = fromSel.options.length - 1; i >= 0; i--) {
                var opt = fromSel.options[i];
                if (opt.selected) {
                    if (opt.value === 'temp') {
                        alert('提示項目不可移動!');
                        return;
                    }
                    // 建立新選項並加入目標
                    toSel.options.add(new Option(opt.text, opt.value));
                    // 從來源移除
                    fromSel.remove(i);
                    moved = true;
                }
            }

            if (!moved) {
                alert('請先選擇要移動的項目!');
            }
        }

        // 提交前:全選右側所有項目,並寫入隱藏欄位
        function prepareSubmit() {
            var rightSel = document.getElementById('rightSelect');
            var hidden = document.getElementById('hiddenValues');
            
            // 全選
            for (var i = 0; i < rightSel.options.length; i++) {
                rightSel.options[i].selected = true;
            }
            
            // 收集值
            var vals = [];
            for (var i = 0; i < rightSel.options.length; i++) {
                vals.push(rightSel.options[i].value);
            }
            hidden.value = vals.join(',');
            
            alert('將提交的值: ' + hidden.value);
            return true; // 允許提交 (示範用,實際可改為 AJAX)
        }

        // 手動預覽
        function collectValues() {
            prepareSubmit();
        }
    </script>
</body>
</html>

核心邏輯解析

  1. 反向迴圈:for (var i = len-1; i >= 0; i--) 移除選項時索引不會錯亂。
  2. Option 建構式:new Option(text, value) 為標準建立選項方式,跨瀏覽器相容。
  3. select.options.add() / select.remove():原生 DOM API,無需 jQuery。
  4. 提示項處理:disabled 屬性防止被選中,移動時自動移除。
  5. 表單提交攔截:onsubmit="return prepareSubmit()" 確保隱藏欄位已填值且右側全選。

jQuery 簡潔版 (參考)

function moveOptionsJQ(fromId, toId) {
    var $from = $('#' + fromId);
    var $to = $('#' + toId);
    
    // 移除提示項
    $to.find('option[value="temp"]').remove();
    
    // 移動選中項
    $from.find('option:selected').each(function() {
        $to.append($(this).clone());
        $(this).remove();
    });
    
    if (!$from.find('option:selected').length) alert('請先選擇項目!');
}

// 提交前收集
$('#myForm').on('submit', function() {
    var vals = $('#rightSelect option').map(function() { return this.value; }).get().join(',');
    $('#hiddenValues').val(vals);
    $('#rightSelect option').prop('selected', true);
});

常見擴充需求

  • 排序:移動後按文字/值排序 Array.from(sel.options).sort(...)
  • 搜尋/過濾:在左側上方加入 <input> 即時過濾選項。
  • 拖曳排序:引入 SortableJS 實現右側選項拖曳調整順序。
  • 雙向同步:配合後端 API,移動即同步儲存 (AJAX)。

總結

雙 Select 移動是後台管理系統常見 UI 模式。原生 JS 實作輕量且無依賴,掌握 select.options 操作 API 是關鍵。實務上建議封裝為可復用元件 (Vanilla JS Class / Vue Component / React Component),支援配置化、事件回調、無障礙存取 (ARIA)。

copyright © 萬盛學電腦網 all rights reserved