Get items from Select2 after data has been loaded
Asked Answered
L

1

5

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)

Liliuokalani answered 1/9, 2015 at 15:35 Comment(2)
What version of select2 are you using?Congeries
This one: select2-3.5.1Liliuokalani
C
8

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');
    }
});
Congeries answered 1/9, 2015 at 16:17 Comment(4)
Thanks for your answer. This loads the list of my select then selects automatically the element if there is only one and then it closes the list. But then anytime that I click on the same select that was filtered by another it doesn't allow to open it again, whether if it has one element or more than one. It closes always the select. You know how to avoid this behavior? No matter when I click on the select it raises the select2-loaded and ends to close. I want to diferentiate when the select was filtered by another select or by when I click on it.Liliuokalani
You're right. I've edited my answer and moved the closing inside the if (..==1) statement so it'll only close when there is only 1 item.Congeries
I've already did that. But now if there are more than one element it never closes and stay open. The idea is to set the value and I called the 'open' because that method raises the operation to refresh the data of the select. Maybe there is another way to refresh the data (similar to open) and select the value when it is required.Liliuokalani
Based on this you can try adding right after the open the following line: $(".select").select2({ data: fromAccountData });Congeries

© 2022 - 2024 — McMap. All rights reserved.