How to programmatically inject search queries into Select2 v4?

前端 未结 5 1092
刺人心
刺人心 2020-12-14 16:17

I\'ve built a web-app using a Select2 search box, which connects to our backend via AJAX. The search box passes the query (say \"APPLES\") to the backend, which then updates

5条回答
  •  感动是毒
    2020-12-14 16:41

    As an addition to this answer, we were trying to programmatically add a new 'tag' to a select2 configured for tagging. Instead of triggering a keyup event on the $search box, we had to do the following.

    $search.val(tag);
    $search.closest('.select2-search--inline')
        .trigger($.Event('input', { which: 13 }));
    $search.closest('.select2-selection--multiple')
        .trigger($.Event('keydown', { which: 13 }));
    

    This first fires an event that causes the 'search' module in select2 to add a 'highlighted' result containing the tag text, then the second event causes select2 to fire the 'select' event internally which adds a new tag to the select2 options and may also trigger other stuff, depending on how you've configured it.

提交回复
热议问题