首页 > 解决方案 > HTML 在两个选择列表之间发送值

问题描述

我有这个 Codepen,我需要从第一个列表中选择一个项目,将所选项目发送到第二个,反之亦然。问题是我无法将值返回到第一个列表。请帮忙。

https://codepen.io/anon/pen/oQgmbZ?editors=1010

<select id="S1" multiple class="form-control form-control-sm" style="height:90px; width:100%; min-width:400px; font-size:8pt; text-align:left;" onchange="SelectValues(this)">
  <option value='AAA'>AAA</option>
  <option value='BBB'>BBB</option>

</select> 
<select id="S2" multiple class="form-control form-control-sm" onclick="DeSelectValues();" style="height:90px; width:400px; min-width:400px; font-size:8pt; text-align:left;"></select>

JS:

function DeSelectValues() {
  //get the listbox object from id.
  var src = document.getElementById('S2');

  //iterate through each option of the listbox
  for (var count = src.options.length - 1; count >= 0; count--) {
    //if the option is selected, delete the option
    if (src.options[count].selected == true) {
      try {
        src.remove(count, null);
      } catch (error) {
        src.remove(count);
      }
    }
  }


  //var selval = $("#S2 option:selected");
  //var o = new Option(selval, selval);
  //$(o).html($(selval));
  //$("#A1").append(o);


}

function SelectValues(sel) {
    var selval = $("#S1 option:selected");
    var o = new Option(selval, selval);
    $(o).html($(selval));
    $("#S2").append(o);  
}

标签: javascriptjquery

解决方案


您似乎想将节点从一个移动到另一个。

如果您只是将当前选择的方法的引用传递<option>给该<select>.append()方法,则该节点将被移动。无需克隆选择元素。

function DeSelectValues() {
    var selval = $("#S2 option:selected");
    selval[0].selected = false // deselecting
    $("#S1").append(selval); 
}

function SelectValues(sel) {
    var selval = $("#S1 option:selected");
    selval[0].selected = false // deselecting
    $("#S2").append(selval); 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="S1" multiple class="form-control form-control-sm" style="height:90px; width:100%; min-width:400px; font-size:8pt; text-align:left;" onchange="SelectValues(this)">
  <option value='AAA'>AAA</option>
  <option value='BBB'>BBB</option>
  
</select>




<select id="S2" multiple class="form-control form-control-sm" onclick="DeSelectValues();" style="height:90px; width:400px; min-width:400px; font-size:8pt; text-align:left;"></select>


推荐阅读