Move Selections Between Boxes

by flynn_inc

HTML

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div class="container">
        <!-- Left select box -->
    <table>
    <tr>
        <td>
            <label for="leftBox">Label for Left Box</label>        
        </td>
    </tr>
    <tr>
        <td>
            <select id="leftBox" multiple>
                <option value="1">Apple</option>
                <option value="2">Banana</option>
                <option value="3">Cherry</option>
                <option value="4">Date</option>
                <option value="5">Pinapple</option>
                <option value="6">Blackberry</option>
                <option value="7">Raspberry</option>
                <option value="8">Orange</option>
                <option value="9">Taco</option>
                <option value="10">Grapefruit</option>
                <option value="11">Slice of Pizza</option>
                <option value="12">Shower Curtain Ring</option>
            </select>
        </td>
    </tr>
    </table>

    <!-- Left select box -->
    <select id="leftBox" multiple>
        
    </select>

    <!-- Buttons -->
    <div>
        <button id="moveRight">&gt;&gt;</button>
        <button id="moveLeft">&lt;&lt;</button>
    </div>

    <!-- Right select box -->
    <table>
    <tr>
        <td>
            <label for="rightBox">Label for Right Box</label>        
        </td>
    </tr>
    <tr>
        <td>
            <select id="rightBox" multiple>
                <option value="5">Elderberry</option>
            </select>
        </td>
    </tr>
    </table>
</div>

CSS

select {
        width: 200px;
        height: 150px;
    }
    .container {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    button {
        display: block;
        margin: 5px 0;
        padding: 5px 10px;
    }
    label {
        
    }

JavaScript

$(document).ready(function() {
    // Move selected from left to right
    $("#moveRight").click(function() {
        let selected = $("#leftBox option:selected");
        if (selected.length === 0) {
            alert("Please select at least one item to move.");
            return;
        }
        $("#rightBox").append(selected.clone()); // Clone to preserve original
        selected.remove(); // Remove from left
    });

    // Move selected from right to left
    $("#moveLeft").click(function() {
        let selected = $("#rightBox option:selected");
        if (selected.length === 0) {
            alert("Please select at least one item to move.");
            return;
        }
        $("#leftBox").append(selected.clone());
        selected.remove();
    });
});