caponica
caponica

Reputation: 3958

Select2 - create ajax with pre-loaded options

I have a fairly simple requirement set, but cannot for the life of me figure out how to achieve it with Select2...

  1. I would like to have an input on the page
  2. Which the user can type into to trigger an AJAX call
  3. Which also displays a pre-loaded list of options that the user can click on instead of typing to trigger the AJAX.
  4. If you close (blur) the input and then reopen it again then the previously loaded AJAX responses should still be displayed (instead of the options being blank and you having to start typing to load them again).

I can do #1 and #2 (or #1 and #3 of course!), but I cannot get all three requirements in one input field. I've not found any way to do #4.

Effectively, to achieve #3, I guess I'm looking for a way to inject my shortlist into what are normally the ajax-returned options and use something like #4 to make sure these are not cleared when the field is opened.

Is there a way to initialise the (normally Ajax loaded) options for a Select2 field? I've tried passing in data but it doesn't work, I tried using initSelection until I realised that wasn't relevant, I've tried all sorts of things, but to no avail...

Hopefully this is possible and I've just missed an option somewhere!

P.S. I've read several threads on Stack with similar titles to this but none of them seem to answer this question. If I've missed the vital one just let me know!

Upvotes: 0

Views: 511

Answers (1)

John S
John S

Reputation: 21492

I think you can do this if you use Select2's query option, rather than the ajax option. That way you can make the ajax request if any characters have been typed, but show the default list if no characters have been typed.

If your default options are defined like this:

var DEFAULT_OPTIONS = [
    { id: 'def1', text: 'Default Choice 1' },
    { id: 'def2', text: 'Default Choice 2' },
    { id: 'def3', text: 'Default Choice 3' }
];

You could do the following:

var lastOptions = DEFAULT_OPTIONS;

$('#select').select2({
    minimumInputLength: 0,
    query: function(options) {
        if (options.term) {
            $.ajax({
                type: 'post', // Or 'get' if appropriate
                url: 'your_ajax_url',
                dataType: 'json',
                data: {
                    term: options.term // Change name to what is expected
                },
                success: function(data) {
                    lastOptions = data;
                    options.callback({ results: data });
                }
           });
        } else {
            options.callback({ results: lastOptions });
        }
    }
});

jsfiddle

Upvotes: 1

Related Questions