jquery select2 - not working

user2315153 picture user2315153 · Apr 24, 2013 · Viewed 55.8k times · Source

I am using select2 plugin(ivaynberg.github.io/select2). I am trying to display a dropdown(select). It is getting all the items in data.php as options. However select2 is meant to be autocomplete plugin and should search for the search term a client input, and display the matching results only. At the moment it is displaying all the items and not getting the search results. Sorry for my language

data.php is echoing out this:

[{
    "id": "1",
    "text": "item1",
    "exercise": "blah text"
  }, {
    "id": "2",
    "text": "item2"
  }
]

The code is:

$(document).ready(function () {
    $('#thisid').select2({
        minimumInputLength: 2,
        ajax: {
            url: "data.php",
            dataType: 'json',
            data: function (term, page) {
                return {
                    q: term
                  };
            },
            results: function (data, page) {
                return {
                    results: data
                };
            }
        }
    });
});

and the input is:

<input type="hidden" id="thisid" style="width:300px" class="input-xlarge" />

I want to find a clue, I am quite new to this plugin and have spent a day for looking at examples.

Answer

GGregson picture GGregson · May 2, 2013

select2 will not do AJAX if attached to a standard select form control. It MUST be attached to a hidden input control to load via AJAX.

Update: This has been fixed in Select2 4.0. From Pre-Release notes:

Consistency with standard <select> elements for all data adapters, removing the need for hidden <input> elements.

It can also be seen in function in their examples section.