简体   繁体   中英

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)

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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM