0
タグオプションを使用してSelect2ドロップダウンにカスタム値を動的に設定できません。Select2:タグベースのドロップダウンリストの値を更新できません
既存の値のいずれかを設定した場合にのみ機能します。したがって、可能な解決策の1つは、&を選択するオプションを動的に追加し、新しい値を設定することです。
HTML
<select id="list" name="nombres" style="width:50%"></select>
<br>
<button id="existing">Existing</button>
<button id="custom">Custom</button>
ジャバスクリプト
$(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/
UPDATE - (その後、値を選択するオプションを動的&を追加)上記の手法を添加した溶液
$("#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/
のために仕事を始めたが、元の問題に対処していません。これはすでに言及した回避策です。 – addmaths07