select多选option左右上下移动示例

  select多选option在2个select间左右移动,将选中的option上下移动示例

<title>select多选option左右移动示例_JavaScript/Ajax_Web开发网</title>
<table border="1">
    <tr>
        <td>
            <select multiple size="10" id="s1">
                <script>
                    for (var i = 0; i < 15; i++) document.write('<option>' + i + '</option>')
                </script>
            </select>
        </td>
        <td valign="middle" align="center">
            <input type="button" value=">>" onclick="moveItems(true, true)" /><br /><input type="button" value="<<" onclick="moveItems(false, true)" /><br />
            <input type="button" value=">" onclick="moveItems(true)" /><br /><input type="button" value="<" onclick="moveItems()" /><br />
            <input type="button" value="∧" onclick="moveUpDown()" /><br /><input type="button" value="∨" onclick="moveUpDown(true)" />
        </td>
        <td><select multiple size="10" id="s2"></select></td>
    </tr>
</table>
<script>
    document.getElementById('s1').onclick = document.getElementById('s2').onclick = function () {//控制只能同时选择一边,要不上下移动分别需要2组按钮来控制
        var opt = document.getElementById(this.id == 's1' ? 's2' : 's1').options;
        for (var i = 0; i < opt.length; i++) opt[i].selected = false;
    }
    function moveItems(toRight,isAll) {
        var source = document.getElementById(toRight ? 's1' : 's2'), target = document.getElementById(toRight ? 's2' : 's1');
        for (var i = 0; i < source.options.length;) {
            if (source.options[i].selected || isAll) {
                target.appendChild(source.options[i]);
            }
            else i++;
        }
    }
    function moveUpDown(isDown) {
        var s1 = document.getElementById('s1'), s2 = document.getElementById('s2'), o, selectedIndex;
        if ((selectedIndex = s1.selectedIndex) != -1) o = s1;
        if (selectedIndex == -1 && (selectedIndex = s2.selectedIndex) != -1) o = s2;

        if (o) {
            var endSelectdIndex;
            for (var i = selectedIndex; i < o.options.length; i++) if (o.options[i].selected) endSelectdIndex = i;
            if (!isDown && selectedIndex == 0) alert('已经最前!');
            else if (isDown && endSelectdIndex == o.options.length - 1) alert('已经最后!');
            else {
                var opt = o.options[isDown ? endSelectdIndex + 1 : selectedIndex - 1];
                if (isDown) {
                    o.insertBefore(opt, o.options[selectedIndex]);
                }
                else {
                    var opts = [];
                    for (var i = selectedIndex; i <= endSelectdIndex; i++) opts[opts.length] = o.options[i];
                    for (var i = 0; i < opts.length; i++) o.insertBefore( opts[i],opt);
                }
            }
        }
    }
</script>

 



原创文章,转载请注明出处:select多选option左右上下移动示例
评论(0)Web开发网
阅读(67)喜欢(0)不喜欢(0)JavaScript/Ajax