【问题标题】:Use JQuery to set the select option value and text from Array使用 JQuery 从 Array 中设置选择选项值和文本
【发布时间】:2014-07-28 10:46:00
【问题描述】:

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

我想知道如何使用此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>

如果我在 JS 代码中选择选项 X 和 Y 我的 selected 数组输出如下:

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

然后如何使用这些值来填充另一个下拉列表?我正在尝试从列表功能类型的事物中实现 ADD/REMOVE。

编辑:DROPDOWN 2 的预期输出

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

【问题讨论】:

  • 请添加预期输出(例如 dropdown2 的 html 应该是什么样子)
  • @user574632 我已经做到了
  • id 必须是唯一的,更改第二个选择的名称。我认为这是一个错字。

标签: javascript php jquery arrays


【解决方案1】:

ID 应该是唯一的id="compresult"&gt;

 $('#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 

});

UPDATED DEMO

【讨论】:

  • @Javacadabra 。什么都别想,我认为与其他解决方案相比,这是最好的解决方案,它可能对搜索用户非常有用
【解决方案2】:

只需在循环中构建 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);
});

【讨论】:

    【解决方案3】:

    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);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多