14

I'm trying to populate a select2 element with a JSON array; but I can't get it.

I have the next array:

data = [{"id":"Foo","text":"Foo"},{"id":"Bar","text":"Bar"}]

And I initialize select2 as follow:

$("#selectElement").select2();

I use the next code to populate:

$('#selectElement').select2('data', data, true);

But doesnt work and I dont know why. Someone can help me?

EDIT: I need to populate after the init of select2 (I receive JSON from AJAX)

My intention is populate the select2 of my question with the JSON of the AJAX search of other select2.

All works well except the populate (I get this JSON well in the formatSelectiom method of the first but i dont know that can i do to populate the second select2 with this)

james fray
  • 191
  • 1
  • 2
  • 13

4 Answers4

13

I see some differences between your code and the one from select2

Your data:

var data = [{"id":"Foo","text":"Foo"},{"id":"Bar","text":"Bar"}];

Should be:

var data = [{id:"Foo", text:"Foo"},{id:"Bar", text:"Bar"}]

Your population code:

$('#selectElement').select2('data', data, true);

Should be:

$('#selectElement').select2({data: data});

Example from Select2

var data = [
      { id: 0, text: 'enhancement' }, 
      { id: 1, text: 'bug' }, 
      { id: 2, text: 'duplicate' }, 
      { id: 3, text: 'invalid' }, 
      { id: 4, text: 'wontfix' }
];

$(".js-example-data-array").select2({
  data: data
});

<select class="js-example-data-array"></select>
Mivaweb
  • 5,580
  • 3
  • 27
  • 53
  • Thanks, but I receive JSON from AJAX, so I need initialize select2 before and populate after... May you edit your code, please? – james fray May 28 '15 at 07:30
  • @jamesfray what about using the builtin ajax function of select2 to populate your select? – Mivaweb May 28 '15 at 07:40
  • 1
    I use this in other select2 who retrieves me the JSON. My intention is populate the select2 of my question with the JSON of the AJAX search of the first (sorry for my bad english). All works well except the populate (i get this JSON well but i dont know that can i do to populate the second select2 with this) – james fray May 28 '15 at 07:45
  • And its not working also if you use `$('#selectElement').select2({data: data});`, where data is your json object? – Mivaweb May 28 '15 at 07:47
  • 2
    Nope, doesnt work. Show me the error: option data is not allowed for select2 when attached to a select element – james fray May 28 '15 at 07:49
  • And what if you destroy it first and then populate it using the command above? Destroy: `$example.select2("destroy");` – Mivaweb May 28 '15 at 07:53
  • Check the solution in this thread if that helps: http://stackoverflow.com/questions/15454383/select2-how-to-set-data-after-init – Mivaweb May 28 '15 at 07:57
  • Thanks, but... There is no way to populate with JSON directly? I dont like append the option as in that link... It seems very raw. I hope someon can help me with this problem... Thanks for all your time – james fray May 28 '15 at 08:04
0

I just posted a similar question to the select2 list and then went back to beating my head against the wall. This is what I came up with: (the "destroy" was the tip that helped). First I empty the select and then reset it.

    $("#id_category").on('change', function(){
           var cat = $(this).val();
           var url = '/breeds/lookup/?q='+cat;
           $.get(url, function(d){
               var idb = $("#id_breed").empty();
               idb.select2({data: d});
           }, "json");

        });
Lee Hinde
  • 1,043
  • 12
  • 13
  • 1
    Thanks for your response, but doesnt work... :( I'm desperate (May you put this on a Jsfiddle?is weird it works for you – james fray May 29 '15 at 06:51
0
    $('#selectElement').select2({
                minimumInputLength: 1,
                ajax: {
                    url: '@Url.Action("Search", "Home")',
                    dataType: 'json',
                    data: function(params) {
                return {
                    ad: params.term
                };
            },
            processResults: function(data) {
                return {
                    results: $.map(data, function(obj) {
                        return { id: obj.Id, text: obj.Ad + " " + obj.Soyad };
                    })
                };
            }
            });
0

If you are trying to show drop-down with pre-loaded JSON by default, so the moment you click on field you expect drop-down with populated data to show up, without typing in a single letter, Set:

minimumInputLength: 0

and works like a charm. I hope that solved your issue because it did mine :)

StefaDesign
  • 929
  • 10
  • 19