还是那位博主的一篇关于JavaScript js 左右移动下拉列表选项的文章,我也用自己的方法实现了一下,感觉还是使用js原生的方法比较方便、简单。
这个js的效果是,点击》按钮,使左边列表中被选中项添加到右边的列表,并移除左边列表中的选中项;反之,点《按钮,使右边列表中被选中项添加到左边的列表,并移除右边列表中被选中项。两个列表支持多选。
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>addMulitOptions.html</title>
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="this is my page">
- <meta http-equiv="content-type" content="text/html; charset=UTF-8">
- <script type="text/javascript">
- // 移動id為from的列表中的選中項到id為to的列表中
- function move(from,to) {
- // 獲取移動源
- var fromBox = document.getElementById(from);
- // 獲取移動目的地
- var toBox = document.getElementById(to);
- // 當移動源存在選中項時
- while(fromBox.selectedIndex != -1){
- // 將移動源中的選中項添加到移動目的地的末尾
- toBox.appendChild(fromBox.options[fromBox.selectedIndex]);
- }
- }
- // 移動id為from的列表中的所有項到id為to的列表中
- function moveAll(from,to) {
- // 獲取移動源
- var fromBox = document.getElementById(from);
- // 獲取移動目的地
- var toBox = document.getElementById(to);
- // 當移動源存在項時
- while(fromBox.options.length > 0){
- // 將移動源中的第一項添加到移動目的地的末尾
- toBox.appendChild(fromBox.options[0]);
- }
- }
- </script>
- </head>
- <body>
- <select id="leftBox" multiple="multiple" style="height: 200px; width: 100px;">
- <option value="1">a</option>
- <option value="2">b</option>
- <option value="3">c</option>
- <option value="4">d</option>
- </select>
- <input type="button" value=">" onclick="move('leftBox','rightBox')"/>
- <input type="button" value="<" onclick="move('rightBox','leftBox')"/>
- <input type="button" value=">>" onclick="moveAll('leftBox','rightBox')"/>
- <input type="button" value="<<" onclick="moveAll('rightBox','leftBox')"/>
- <select id="rightBox" multiple="multiple" style="height: 200px; width: 100px;">
- <option value="11">A</option>
- <option value="22">B</option>
- <option value="33">C</option>
- <option value="44">D</option>
- </select>
- </body>
- </html>