javascript - 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);
}
解决方案
您似乎想将节点从一个移动到另一个。
如果您只是将当前选择的方法的引用传递<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>
推荐阅读
- python - 如何在使用指数中的新参数训练神经网络时处理 PyTorch 中的“nan”值?
- javascript - SyntaxError: Missing catch or finally after try ,Discord.js
- mongodb - 错误:架构中未找到对象类型“任务”
- c# - 当我们有由数据库数据计算的列时,如何在 closedXML 中添加注释?
- cookies - 带有 apollo 客户端的 httponly cookie
- scala - 二维数组的 Scala 用户输入
- python - 在 python 中将列表转换为张量时出错
- c++ - 如何在 Maskcrnn libtorch 中获取元组对象返回的值
- ios - 用户选择通知操作后,iOS 在后台发布数据
- java - Java 泛型:不兼容的类型:捕获和