使用JQuery设置选择选项值和Array中的文本


Use JQuery to set the select option value and text from Array

我有一个select框,从中获取multiple值,并使用JQuery将其存储在Array中。

我想知道如何使用此Array的内容在另一个选择框中填充options

所以目前我有这个:

 $('#addBtn').click(function(e){
        e.preventDefault();
        //Get the selected Items in the dropdown 1
        var selected = new Array();
        $('#compresult option:selected').each(function(){
            selected.push($(this).val() + " " + $(this).text());//Add to Array
        });
        //Update contents of dropdown 2  with the Array 
     });

我的下拉菜单HTML是:

<select multiple="multiple" name="contributors[]" id="compresult">
    <option value="0"></option>
    <option value="3610">X</option>
    <option value="3605">Y</option>
    <option value="335">Z</option>
 </select>

如果我选择选项X和Y,我的JS代码中的selected数组将输出以下内容:

Array [ "3610 X", "3605 Y" ]

然后我如何使用这些值来填充另一个下拉列表?我正在尝试实现一个添加/删除列表功能类型的东西。

编辑:下拉列表2 的预期输出

<select multiple="multiple" name="dropdown2" id="compresult">
        <option value="3610">X</option>
        <option value="3605">Y</option>
</select>

ID应该是唯一的id="compresult">

 $('#addBtn').click(function (e) {
    e.preventDefault();
    var selected = $('#compresult option:selected').clone(); // get the selected option and copy that element 
    $("#compresult1").html(selected); // insert into new dropdown list 
});

更新演示

只需在循环中构建html字符串:

$('#addBtn').click(function(e){
    e.preventDefault();
    //Get the selected Items in the dropdown 1
    var drop2html = '';
    $('#compresult option:selected').each(function(){
        drop2html += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>';
    });
    $('#drop2').html(drop2html);
});

push行更改为

selected.push([$(this).val(), $(this).text()]);

因此,我们将选项值和文本分别保存,而不是连接为一个字符串。

然后,创建新的select(你没有说你是想创建一个新的还是填充一个现有的——我假设是后者(:

var other_sel = $('#other_select').empty();
$.each(selected, function(i, arr) {
    $('<option /', {value: arr[0], text: arr[1]}).appendTo(other_sel);
});