weixin_33697898 2017-11-27 22:31 采纳率: 0%
浏览 10

Select2与ajax选项

I have been using selec2 version 4 with ajax option. And I want to set a selected value, as recommended in the guideline, by adding new Option element.

A problem I have is that I do not know when to add the new option because the event select2-loaded does not seem to exist in the latest version of select 2.

Can you please let me know in what way I can know the moment when data has finished loading from the server and has finished setting up, so I can add a new option to it?

Thank you.

  • 写回答

1条回答 默认 最新

  • 喵-见缝插针 2018-01-15 10:01
    关注

    The Option element you mention is created by calling the Option() constructor which then constructs a HTMLOptionElement. So basically you are just adding to your DOM and don't need to do it in any select2 event. Instead just do it on document load.

    Here's a very basic example of what it could look like:

    $(function () {
        $('#element-to-select').select2();
    
        var option = new Option('text', 'value', true, true);
        $('#element-to-select').append(option).trigger('change');
    }
    

    Note that we are calling .trigger('change') to report the change to select2 as documented here.

    评论

报告相同问题?