Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 4.0 initial value in ajax mode

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?

like image 544
Eddie Avatar asked Oct 15 '25 17:10

Eddie


2 Answers

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.

like image 119
Kevin Brown-Silva Avatar answered Oct 18 '25 10:10

Kevin Brown-Silva


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.

like image 24
developius Avatar answered Oct 18 '25 11:10

developius