Populate Select2 with AJAX data
Asked Answered
U

3

5

I'm using Select2 4.0.0-rc.2.

The Options page states the following about initSelection

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.

I only found examples for older versions of Select2 that use initSelection (see Setting initial values on load with Select2 with Ajax)

How can I load default data with data adapter?

here is my initial code (is twig)

 $("#{{ id }}").select2({
            ajax: {
                    url: "{{ path(attr.path) }}",
                    dataType: 'json',
                    {% if attr.placeholder is defined %}
                    placeholder: '{{ attr.placeholder }}',
                    {% endif %}
                    delay: 250,
                    data: function (term) {
                        return term;
                    },
                    processResults: function (data) {
                        return {results: data};
                    }

                },
            templateResult: function(data){
                return '<img width="30" src="'+data.image+'">'+data.text;
            },
            templateSelection: function(data){
                return '<img width="30" src="'+data.image+'">'+data.text;
            },

            cache: true,
            escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
            minimumInputLength: 2
        });

If it possible i want setup always visible options and have ajax other,

Usm answered 20/4, 2015 at 13:53 Comment(0)
E
5
<select id="posow"></select>

for above select i do like this:

$(function () {
            $.getJSON( "/f3/tokenize/PO_SoW", function(respond) {
                $('#posow').select2({
                    multiple: true,
                    data: respond
                });
             });
});

respond from server is this:

[{id: 'nms', text: 'FATP'},
{id: 'nms', text: 'ATF Plan'},
{id: 'nms', text: 'Endorse Plan'},
{id: 'nms', text: 'Endorse Date'}
]
Emersen answered 23/12, 2015 at 13:35 Comment(0)
K
3

You have a detailed explanation on their docs. If you only need to load your data once you can do that using the following code (that was stripped from their docs page):

var $element = $('select').select2(); // the select element you are working with

var $request = $.ajax({
  url: '/my/remote/source' // wherever your data is actually coming from
});

$request.then(function (data) {
  // This assumes that the data comes back as an array of data objects
  // The idea is that you are using the same callback as the old `initSelection`

  for (var d = 0; d < data.length; d++) {
    var item = data[d];

    // Create the DOM option that is pre-selected by default
    var option = new Option(data.text, data.id, true, true);

    // Append it to the select
    $element.append(option);
  }

  // Update the selected options that are displayed
  $element.trigger('change');
});
Kellda answered 21/4, 2015 at 21:55 Comment(4)
i want setup initial data to ajax input, i read doc but dont know how to do it. i add my setup code.Usm
Yeah, docs are not great IMHO. How in the world do you even use (add) an adapter? Are there docs for the config on this?Blackmail
Did you ever figure out how to code / add an adapter? I don't get how custom data adapters support AJAX, as the whole point of AJAX is to only fire the callback when the requests are done. I am probably just not as smart as the guy who designed this?Kubis
Well done! It works. Only be careful: var option = new Option(item.text, item.id, true, true);Hammons
A
0

As a continuation of Milz's answer I would add that you need to append an empty value at the end otherwise the last value will never be selected.

  ...

  for (var d = 0; d < data.length; d++) {
    var item = data[d];

    // Create the DOM option that is pre-selected by default
    var option = new Option(data.text, data.id, true, true);

    // Append it to the select
    $element.append(option);
  }

  var option = new Option('', '', true, true);
  $element.append(option);

  ...

Maybe there is some other way to do it but this did the trick for me.

Afterword answered 1/9, 2015 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.