Gerstner Tamás
Gerstner Tamás

Reputation: 31

select2 set initial value with ajax load, and custom template

I tried many things. i cant initialize default selected items. The values always "undefined".

Can anyone please help me?

i create de select2, and add options for select.

var selected = [{
    "id": 50270924,
    "full_name": "zquestz/s",
    "description": "Open a web search in your terminal.",
    "language": "Go"
        }, {
    "id": 30494317,
    "full_name": "haosdent/s",
    "description": "s is a tool for ssh like z for cd",    
    "language": "Shell"
    }];

var $gitElement = $(".select2").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term,
        page: params.page
      };
    },
    processResults: function (data, page) {
      return {
        results: data.items
      };
    },
    cache: true
  },
  data:selected,
  escapeMarkup: function (markup) { return markup; }, 
  minimumInputLength: 1,
  templateResult: function(repo) {
    console.log("res", repo, this);
    return '<div class="select2CompanyName">'+repo.full_name+'</div>' +
           '<div class="select2CompanyTitle">'+repo.language+'</div>' +
           '<div class="select2CompanyTitle">'+repo.description+'</div>';
  },
  templateSelection: function(repo) {
    console.log("sel", repo, this);
    return '<div class="select2CompanyResult">' +
        '<div class="select2CompanyName">'+repo.full_name+' <br>'+ repo.language +'</div>' +
        '<i class="fa fa-pencil-square-o"></i>' +
            '</div>';
  }
});

for(var i in selected) {
    $(".select2").append('<option value="'+selected[i].id+'" selected="selected"></option>');
}

$(".select2").trigger("change");

this version: jsfiddle

ugly solution would be:

for(var i in selected) {
    $(".select2").append('<option value="'+selected[i].id+'" selected="selected">'+JSON.stringify(selected[i])+'</option>');
}

here working, but ugly

Upvotes: 1

Views: 1762

Answers (1)

NewBee
NewBee

Reputation: 1469

there got a simple way to fix it, u just need to move your template logic to processResults, code should be something like :

function displayItem(repo) {
return {
    id : repo.id,
  text : '<div class="select2CompanyName">'+repo.full_name+'</div>' +
       '<div class="select2CompanyTitle">'+repo.language+'</div>' +
       '<div class="select2CompanyTitle">'+repo.description+'</div>'
};
}

....

processResults: function (data, page) {
      return {
        results: $.map(data.items, displayItem);
      };
    },

Cost me sometime to find the issue.. I upgrade select2 version to 4.0.2. check fiddle here

Upvotes: 1

Related Questions