Moving items in Dual Listboxes

我怕爱的太早我们不能终老 提交于 2019-11-27 19:26:40

This code assumes that you have an anchor or that will trigger to movement when it is clicked:

document.getElementById('moveTrigger').onclick = function() {

    var listTwo = document.getElementById('secondList');
    var options = document.getElementById('firstList').getElementsByTagName('option');

    while(options.length != 0) {
        listTwo.appendChild(options[0]);
    }

 }
Remy Sharp

If you're happy to use jQuery, it's very, very simple.

$('#firstSelect option:selected').appendTo('#secondSelect');

Where #firstSelect is the ID of the select box.

I've included a working example here:

http://jsbin.com/aluzu (to edit: http://jsbin.com/aluzu/edit)

A library-independent solution:

function Move(inputControl)
{
  var left = document.getElementById("Left");
  var right = document.getElementById("Right");
  var from, to;
  var bAll = false;
  switch (inputControl.value)
  {
  case '<<':
    bAll = true;
    // Fall through
  case '<':
    from = right; to = left;
    break;
  case '>>':
    bAll = true;
    // Fall through
  case '>':
    from = left; to = right;
    break;
  default:
    alert("Check your HTML!");
  }
  for (var i = from.length - 1; i >= 0; i--)
  {
    var o = from.options[i];
    if (bAll || o.selected)
    {
      from.remove(i);
      try
      {
        to.add(o, null);  // Standard method, fails in IE (6&7 at least)
      }
      catch (e)
      {
        to.add(o); // IE only
      }
    }
  }
}

HTML

<select id="Left" multiple="multiple" size="10">
  <option>Some</option>
  <option>List</option>
  <option>Of</option>
  <option>Items</option>
  <option>To</option>
  <option>Move</option>
  <option>Around</option>
</select>

<div id="Toolbar">
  <input type="button" value="&gt;" onclick="Move(this)"/>
  <input type="button" value="&gt;&gt;" onclick="Move(this)"/>
  <input type="button" value="&lt;&lt;" onclick="Move(this)"/>
  <input type="button" value="&lt;" onclick="Move(this)"/>
</div>

<select id="Right" multiple="multiple" size="10">
</select>

CSS (example)

select { width: 200px; float: left; }
#Toolbar { width: 50px; float: left; text-align: center; padding-top: 30px; }
#Toolbar input { width: 40px; }

Quick test FF3 and IE6 & 7 only.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!