[Solved] how to swap two dropdownlists with one button using javascript [closed]


You could do this as follows:

HTML

<table>
    <tr>
        <td>
            <select id="mySelect1" size="5" multiple style="width:200px">
                <option value="opt1">Option 1</option>
                <option value="opt2">Option 2</option>
                <option value="opt3">Option 3</option>
            </select>
        </td>
        <td valign="center">
            <button id="toRight">►</button><br/>
            <button id="toLeft">◄</button>
        </td>
        <td>
            <select id="mySelect2" size="5" multiple style="width:200px">
                <option value="opt4">Option 4</option>
                <option value="opt5">Option 5</option>
                <option value="opt6">Option 6</option>
            </select>
        </td>
    </tr>
</table>

Javascript (pure)

function moveOptionsTo(index) {
    var target = document.getElementById('mySelect' + index);
    var options = document.getElementById('mySelect' + (3-index)).options;
    for (var i = 0; i < options.length; i++) {
        if (options[i].selected) {
            target.appendChild(options[i]);
            i = i - 1;
        }
    }
}
document.getElementById('toRight').onclick = function() {
    moveOptionsTo(2);
};
document.getElementById('toLeft').onclick = function() {
    moveOptionsTo(1);
};
document.getElementById('mySelect1').ondblclick = function() {
    moveOptionsTo(2);
};
document.getElementById('mySelect2').ondblclick = function() {
    moveOptionsTo(1);
};

Alternative: Javascript with jQuery

function moveOptionsTo(index) {
    $('#mySelect' + (3-index) + ' option:selected').appendTo('#mySelect' + index);
}
$('#toRight').click(function() {
    moveOptionsTo(2);
});
$('#toLeft').click(function() {
    moveOptionsTo(1);
});
$('#mySelect1').dblclick(function() {
    moveOptionsTo(2);
});
$('#mySelect2').dblclick(function() {
    moveOptionsTo(1);
});

Here is a fiddle using the above code. This allows multi-select and double-click on items or button to move.

solved how to swap two dropdownlists with one button using javascript [closed]