【发布时间】: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");
});
【问题讨论】:
标签: jquery select jquery-select2 dropdown