Álvaro González
Álvaro González

Reputation: 146578

Make Select2 fetch data only once

I'm using Select2 builtin AJAX to load a tiny list of items. Select2 loads the entire list on first selection (good) but reloads the JSON feed every time the user tries to change his selection or type to filter items (and that means a new AJAX request for each typed letter!).

At A request is being triggered on every key stroke, can I delay this? we can read:

By default, Select2 will trigger a new AJAX request whenever the user changes their search term. You can set a time limit for debouncing requests using the ajax.delay option.

$('select').select2({
    ajax: {
        url: '/example/api',
        delay: 250
    }
});

This will tell Select2 to wait 250 milliseconds before sending the request out to your API.

... but it doesn't. Seriously. I've also tried the undocumented minimumInputLength property shown in examples but it doesn't seem to do anything.

Is it even possible to make Select2 fetch data only once?

Upvotes: 2

Views: 2451

Answers (3)

Philipp Poropat
Philipp Poropat

Reputation: 141

The select2 ajax parameter sets off the ajax call every time the user changes her/his input. If you want to load your list only once, just load it via a normal ajax call when your page is loaded and set the result into the data attribute of your select2 like this:

var dataList;

$.ajax({
   url : '/example/api',
   success : function(data) {
      dataList = data;
   },
   async : false
});

$('select').select2({
   data: dataList
});

Upvotes: 1

POTI RN
POTI RN

Reputation: 11

Let me know if this solution would work for you:

1) bind an onChange action to your select element:

        <select name="variable" onChange="loadyourlist($('option:selected',this).val());">
            <option value="#">Select State</option>
            <option value="1">State 1</option>
        </select>

2) Make your request inside loadyourlist function, but check if it has been called before:

        window.called = 0; //initial state

        function loadyourlist(value){
            if(!window.called){  //not called before
                //make your ajax call
                window.called = 1; //increment to avoid furter calls
            }
        }

Upvotes: 0

Darren Parker
Darren Parker

Reputation: 1812

It is working for me. I tested it using a large delay: delay: 3000 The AJAX reqeust is indeed delayed 3 secs after the last keystroke. It also works when deleting characters with the backspace key. I'm using select2.full.js v4.0.3. Hope this helps.

Upvotes: 0

Related Questions