Search code examples
html-selectprototypejs

Prototype: how to move selected options from one select to another?


Using prototype 1.6 how can I remove all selected options from one select and append them to another? I guess I should add that when they show up in the target they should not be selected...


Solution

  • I found the answer, which involved just using "plain-jane" javascript to get the selected options and de-select them. This uses prototype 1.6 and works fine.

    <head>
    
        <script type="text/javascript" src="prototype.js"></script>
    
    </head>
    
    <body>
    
        <h1>Hello World</h2>
    
        <div style="border:solid 1px black">
    
            <select id="leftSelect" multiple="multiple" size="3">
                <option value="1">One</option>
                <option value="2">Two</option>
                <option value="3">Three</option>
            </select>
    
            <span class="test">
                <button id="moveRightBtn">&gt;&gt;</button><br/>
                <button id="moveLeftBtn">&lt;&lt;</button>
            </span>
    
            <select id="rightSelect" multiple="multiple" size="3">
                <option value="1">One</option>
                <option value="2">Two</option>
                <option value="3">Three</option>
            </select>
    
        </div>
    
        <script type="text/javascript">
    
            document.observe("dom:loaded", function()
            {
                Event.observe("moveRightBtn", "click", function()
                {
                    move($("leftSelect"), $("rightSelect"));
                });
    
                Event.observe("moveLeftBtn", "click",  function()
                {
                    move($("rightSelect"), $("leftSelect"));
                });
            });
    
            function move(sourceSelect, targetSelect)
            {
            var options = sourceSelect.select("option");
    
            options.each(function(item)
            {
               if(item.selected)
               {
                  item.selected = false;
                  targetSelect.appendChild(item.remove());
               }
            });
            }
    
        </script>
    
    </body>