我正在嘗試將一些預選值填充到Select2。我的代碼如下。
(function($) {
$(document).ready(function() {
$(".volunteer").on("click", function (event) {
let element_id = event.target.id;
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
// Populate select element
cellEle.html(`<select multiple="multiple"></select>`);
// Initialise select2
let selectEle = cellEle.children("select").select2({
allowClear: true,
maximumSelectionLength: 3,
ajax: {
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
dataType: 'json',
data: function (params) {
return {
action: 'get_data',
};
},
type: "post",
processResults: function (data) {
var options = [];
if ( data ) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
return {
results: options
};
}
}
});
selectEle.select2('open');
$.ajax({
type: "POST",
dataType: 'json',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
element_id: element_id,
action: 'get_preselect_values',
},
success: function (data) {
var options = [];
if (data) {
$.each( data, function( index, text ) {
options.push({ id: index, text: text });
});
}
selectEle.val(options).trigger('change'); // I am trying to attach value here. But it is not working.
}
});
selectEle.on('select2:select', function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
element_id: element_id,
action: 'save_data'
}
});
});
selectEle.on("select2:unselecting", function () {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
data: {
selected_items: selectEle.val(),
task_id: element_id,
action: 'save_data'
}
});
}).trigger('change');
}
});
});
})(jQuery)
我正在嘗試附加值,但它不起作用。
我試影像這樣。
uj5u.com熱心網友回復:
選項應附加到 select 元素,而不是使用.val(). 可以在此處的檔案中找到有關這方面的詳細資訊。
.append預選值的更新代碼片段:
$.ajax({
type: "POST",
dataType: "json",
url: "url",
data: {
element_id: element_id,
action: "get_preselect_values",
},
success: function (data) {
if (data) {
$.each( data, function( index, text ) {
// Declare a new Option for the value - Note id is set to text
const option = new Option(text, text, true, true);
// Append the value to the select element
selectEle.append(option).trigger('change');
});
}
}
});
請注意id,預選值的 必須與id檢索到的值串列相匹配。該id在的問題是,陣列中的項,whcih將不匹配預選索引的索引。如果這些值不匹配,您將能夠選擇預選專案兩次。
為確保值匹配,您可以更新代碼以將 設定id為與text. 添加值時需要這樣做options.push({ id: text, text: text });。在按照上面的示例預選值時也必須這樣做,new Option(text, text, true, true);其中text作為Option的文本和值傳遞。
此外,您可能希望在初始化 select2 之前加載已選擇的值,否則這些值可能會在 select2 打開后出現,這可能會導致意外行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/403802.html
標籤:
