Programmatic selection of select2 which retrieves its data via Ajax

后端 未结 4 1705
野趣味
野趣味 2021-02-19 10:16

I am using select2 version 4.0, and I am trying to make a programmatic selection to a select box which gets its data from an ajax call.

In the documentation, I found how

4条回答
  •  孤街浪徒
    2021-02-19 10:49

    I would also love to know a full answer to this, but here's a partial solution:

    $('#select2-control-id').val('item-id').trigger('select2:select').trigger('change');
    

    This only seems to work if the select2 has already loaded the item you're asking for - i.e. it's one you've already clicked on.

    Not only do you have to have manually opened the dropdown so it will load the first page of items via AJAX - you also have to have actually clicked on the one you want to programmatically select later.

    This appears to be because it only adds to the underlying select element when you actually click on them.

    I can't see a way to programmatically tell select2 to load the first page of AJAX results.

提交回复
热议问题