Trigger an action after selection select2

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I am using select2 library for my search.
is there any way to trigger an action after selecting a search result? e.g. open a popup, or a simple js alert.

$("#e6").select2({     placeholder: "Enter an item id please",     minimumInputLength: 1,     ajax: { // instead of writing the function to execute the request we use Select2's convenient helper         url: "index.php?r=sia/searchresults",         dataType: 'jsonp',         quietMillis: 3000,         data: function (term, page) {         return {             q: term, // search term             page_limit: 10,             id: 10             };         },         results: function (data, page) { // parse the results into the format expected by Select2.             // since we are using custom formatting functions we do not need to alter remote JSON data             return {results: data};         },     },      formatResult: movieFormatResult, // omitted for brevity, see the source of this page     formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page     dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller     escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results }); 

回答1:

See the documentation events section

Depending on the version, one of the snippets below should give you the event you want, alternatively just replace "select2-selecting" with "change".

Version 4.0 +

Events are now in format: select2:selecting (instead of select2-selecting)

Thanks to snakey for the notification that this has changed as of 4.0

$('#yourselect').on("select2:selecting", function(e) {     // what you would like to happen }); 

Version Before 4.0

$('#yourselect').on("select2-selecting", function(e) {     // what you would like to happen }); 

Just to clarify, the documentation for select2-selecting reads:

select2-selecting Fired when a choice is being selected in the dropdown, but before any modification has been made to the selection. This event is used to allow the user to reject selection by calling event.preventDefault()

whereas change has:

change Fired when selection is changed.

So change may be more appropriate for your needs, depending on whether you want the selection to complete and then do your event, or potentially block the change.



回答2:

There was made some changes to the select2 events names (I think on v. 4 and later) so the '-' is changed into this ':'.
See the next examples:

$('#select').on("select2:select", function(e) {      //Do stuff }); 

You can check all the events at the 'select2' plugin site: select2 Events



回答3:

It works for me:

$('#yourselect').on("change", function(e) {     // what you would like to happen }); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!