question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Select2 load default data in multiple select with ajax

See original GitHub issue

I’m using select2 4.0.0.

<select id="mySelect" class="form-control" multiple="multiple"></select>
$('#mySelect').select2({
      width: '100%',
      data: data,
      ajax: {
           url: function() { return 'myendpoint' ; },
           dataType: 'json',
           delay: 250,
           data: function (params) {
               return {
                   where: {'title' : '%' + params.term + '%'}, 
                       page: params.page
               };
          },
          processResults: function (data, params) {

            params.page = params.page || 1;
            return {
                results: $.map(data.message.data, function (item) {
                     return {
                          text: item.values.title,
                          id: item.values.id
                     }
                }),
                pagination: {
                     more: (params.page * 30) < data.total_count
                   }
               };
           },
           cache: true
           },
           minimumInputLength: 1,

       }).val(ids).trigger('change');

This is what i’m tring to do but it seems that it overrides data i’m passing during the inizialization. If I remove the ajax everything seems to work right. My data is an array of object:

[
    { id: '1', text: 'example' }
]

Instead my ids is an array of id [1].

I checkout some other issues in stackoverflow, but others has some different version and use initSelection but it seems don’t work in select2 4.0.0.

Where i’m wrong with this? Thanks.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
danhorton7commented, Feb 22, 2019

@arkid something like this

$('.q').select2({
		ajax: {
		  url: '/api/usersearch',
		  dataType: 'json',
		  delay:300,
		  minimumInputLength: 3
		},
		placeholder: 'Search for a user to assign to'
	  });
	  // Fetch the preselected item, and add to the control
	var userSelect = $('.q');
	$.ajax({
		type: 'GET',
		url: '/api/usersearch/tasks/' + event_id
	}).then(function (data) {
		// create the option and append to Select2
		data.results.forEach(function(d) {
			var option = new Option(d.text, d.id, true, true);
			userSelect.append(option).trigger('change');
		});

		// manually trigger the `select2:select` event
		userSelect.trigger({
			type: 'select2:select',
			params: {
				data: data
			}
		});
});
1reaction
hddung89commented, Nov 5, 2019

@danhorton7 tks for save my day ❤️

Read more comments on GitHub >

github_iconTop Results From Across the Web

select2: default selection in multiple select with AJAX
I would like to programmatically select default values (as in selections the user has made previously), but I don't know how. I read...
Read more >
Ajax (remote data) - The jQuery replacement for select boxes
You can configure how Select2 searches for remote data using the ajax option. Select2 will pass any options in the ajax object to...
Read more >
Add, select, or clear items | Select2 - The jQuery replacement ...
Programmatically adding, selecting, and clearing options in a Select2 control.
Read more >
Basic usage | Select2 - The jQuery replacement for select boxes
Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and pagination (infinite scrolling) of results.
Read more >
Setting initial values on load with Select2 ajax AND templating
then(function (data) { // create the option and append to Select2 var option = new Option(data.full_name, data.id, true, true); // SET CUSTOM ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found