【问题标题】:Select2: Unable to update value of tags based dropdownSelect2:无法更新基于标签的下拉列表的值
【发布时间】:2016-12-29 06:22:47
【问题描述】:

我无法使用标签选项使用自定义值动态填充 Select2 下拉列表。

仅当我设置现有值之一时它才有效。因此,一种可能的解决方案是动态添加选项以选择并设置新值。

HTML

<select id="list" name="nombres" style="width:50%"></select>
<br>
<button id="existing">Existing</button>
<button id="custom">Custom</button>

JavaScript

$(document).ready(function() {
    $("#list").select2({
        placeholder: "Click 'Update'",
        allowClear: true,
        tags: true,
        data:[ 
            "AAA", "BBB", "CCC"
        ]
        });
    $("#existing").on('click', function() {
        $("#list").val("CCC").trigger("change");
    });
    $("#custom").on('click', function() {
        $("#list").val("ZZZ").trigger("change");
    });
});

小提琴:https://jsfiddle.net/mmh2y85h/

更新 - 使用上述方法添加解决方案(动态添加选项然后选择值)

$("#custom").on('click', function() {
        var newVal = '555';
        if ($("#list").find("option[value='" + newVal + "']").length<=0) {
          $("#list").append(new Option(newVal, newVal));
        } 
        $("#list").val(newVal).trigger("change");
});

小提琴:https://jsfiddle.net/8zqegLqm/1/

【问题讨论】:

    标签: jquery select jquery-select2 dropdown


    【解决方案1】:

    我变了

    $("#list").val("ZZZ").trigger("change"); 
    

    $("#list").append("<option>ZZZ</option>");
    

    它开始为我工作https://jsfiddle.net/bindrid/mmh2y85h/1/

    【讨论】:

    • 没有解决原来的问题。这是我已经提到的解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2017-01-14
    相关资源
    最近更新 更多