Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get items from Select2 after data has been loaded

I'm trying to force the open method and select item with select2 like this.

    $(".select").select2('open')
    $(".select").on('select2-loaded', function (e) {
        items = e.items.results;
        if (items.length == 1) {
            $(this).val(items[0].text);
        }
    });
    $(".select").select2('close');

But I cannot get inside the select2-loaded evaluation and the close is happening also to quick. I want to select the first element by default if there is only one element on the list.

When the 'open' occurs, it automatically performs the mechanism to get and load all the elements in my list. If I comment the close method it will take some milliseconds to display the elements on the list.

But what I want is to refresh my list (this is done by the open) then I want to select only if there one element and the close my list ('select')

How can I achieve this? This behaviour will be trigger by a onchange event of another list. (nested selects)

like image 556
Maximus Decimus Avatar asked Sep 01 '15 15:09

Maximus Decimus


1 Answers

You should move the close call INSIDE the select2-loaded event, so it'll only close the select element after it selected the item. Otherwise you're opening, setting event for future event, then closing immediately.

$(".select").select2('open')
$(".select").on('select2-loaded', function (e) {
    items = e.items.results;
    if (items.length == 1) {
        $(this).val(items[0].text);
        $(".select").select2('close');
    }
});
like image 200
uri2x Avatar answered Nov 09 '22 11:11

uri2x