Home > Software engineering >  Populate preselected values to Select2
Populate preselected values to Select2

Time:01-05

I am trying to populate some preselected values to Select2. My code is like below.

(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)

I am trying to attach values but it is not working.

I am trying to something like this.

CodePudding user response:

The options should be appended to the select element rather than selected with .val(). Details on this can be found in the documetation here.

An updated snippet of the code to .append the preselected values:

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

Please note the id of the preselected values must match the id of the retrieved list of values. The id in the question is the index of the item in the array, whcih won't match the preselected index. If these values don't match you'll be able to select preselected items twice.

To ensure the values match you could update your code to set the id to the same string as the text. This would need to be done when adding values options.push({ id: text, text: text });. It must also be done when preselecting values as per the example above new Option(text, text, true, true); where text is passed as both the text and value of the Option.

Additionally you may wish to load the already selected values before initailising select2, otherwise the values may appear after select2 has opened which could cause unexpected behaviour.

  •  Tags:  
  • Related