4xjbh's avatar
Level 4

Preselecting options in an remotely-sourced (AJAX) Select2

I am having trouble working out how to get the request with ManagerID value to ajax when I open a edit form. All of the other controls populate with the correct data.

How do I pass the request data that includes 'ManagerID' value to the ajax fetch below?

OR

Am I going about this the wrong way? TY.

Setup the control

          $('#ManagerID').select2({
              placeholder: "Search for a contact...",
              minimumInputLength: 3,
              theme: "bootstrap",
              ajax : {
                  url : '/api/selectcontact',
                  dataType : 'json',
                  delay : 250,
                  data : function(params){
                      return {
                          q : params.term,
                          page : params.page
                      };
                  },
                  processResults : function(data, params){
                      params.page = params.page || 1;
                      return {
                          results : data.results,
                          pagination: {
                              more : data.pagination.more
                          }
                      };
                  }
              }
          });

Fetch selected item and add to the control

var  managerSelect = $('#ManagerID');
$.ajax({
    type: 'GET',
    url: '/api/selectcontact/s/' + managerid
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name, data.id, true, true);
    managerSelect.append(option).trigger('change');

    // manually trigger the `select2:select` event
    managerSelect.trigger({
        type: 'select2:select',
        params: {
            data: data
        }
    });
});
0 likes
0 replies

Please or to participate in this conversation.