4

I have the following select on my page:

<select><option value="1" selected="selected">Caption</option></select>

I call select2 (v 4.0) init:

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name; },
    templateSelection: function(repo){ return repo.name; }
});

The problem is that select2 is resetting default selected value and showing blank string. Is there any way to set default value on select2 init?

Leith
  • 3,139
  • 1
  • 27
  • 38
Eddie
  • 1,436
  • 5
  • 24
  • 42
  • 1
    I think you might want to use the initSelection option. I don't have a working example off hand but you might want to look into that for your solution. – Jeff Treuting May 20 '15 at 14:49
  • possible duplicate of [Select2 4.0.0 initial value with Ajax](http://stackoverflow.com/questions/30316586/select2-4-0-0-initial-value-with-ajax) – Kevin Brown-Silva May 20 '15 at 15:16

2 Answers2

5

The issue was in your templateSelection method, as you are expecting a name property to be on your data object. Aside from the fact that text is now required and you wouldn't need the method if you re-mapped it, you aren't handling the case where the data object has a text property.

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name || repo.text; },
    templateSelection: function(repo){ return repo.name || repo.text; }
});

This should fix your issue and display the initial selections properly.

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
4

The select2 docs now have an example of how to do this.

// Set up the Select2 control
$('#mySelect2').select2({
  ajax: {
    url: '/api/students'
  }
});

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
  type: 'GET',
  url: '/api/students/s/' + studentId
}).then(function (data) {
  // create the option and append to Select2
  var option = new Option(data.full_name, data.id, true, true);
  studentSelect.append(option).trigger('change');

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

Basically, configure select2 for ajax and then pre-fill with the desired object. The magic is done in the last bit, .trigger() which causes select2 to pick up the change and render it.

developius
  • 1,193
  • 9
  • 17