将预选值填充到 Select2

Populate preselected values to Select2

我正在尝试将一些预选值填充到 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)

我正在尝试附加值,但它不起作用。

我正在尝试 this

选项应附加到 select 元素,而不是 select 与 .val() 一起编辑。有关详细信息,请参阅文档 here

.append 预 select 值的更新代码片段:

$.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');
      });
    }
  }
});

请注意,预select 值的 id 必须与检索到的值列表的 id 匹配。问题中的 id 是数组中项目的索引,与预先 select 编辑的索引不匹配。如果这些值不匹配,您将能够 select 预先select编辑项目两次。

为确保值匹配,您可以更新代码以将 id 设置为与 text 相同的字符串。这需要在添加值 options.push({ id: text, text: text }); 时完成。当按照上面的示例 new Option(text, text, true, true); 预 selecting 值时也必须完成,其中 text 作为 Option.[=23= 的文本和值传递]

此外,您可能希望在初始化 select2 之前加载已经 selected 的值,否则这些值可能会在 select2 打开后出现,这可能会导致意外行为。