Run an action after selecting select2

I am using select2 library for my search.
Is there any way to trigger an action after selecting a search result? like open popup or simple js warning.

$("#e6").select2({ placeholder: "Enter an item id please", minimumInputLength: 1, ajax: { // instead of writing the function to execute the request we use Select2 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 }); 
+47
jquery search jquery-select2
Sep 04 '13 at 13:24
source share
3 answers

See the section on events in the documentation

Depending on the version, one of the snippets below should provide you with the event you need, otherwise just replace “select2-selection” with “change”.

Version 4.0 +

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

Thanks to snakey for notifying me that this has changed from 4.0

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

Version up to 4.0

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

To clarify, the documentation for select2-selecting reads:

Select2-selection Called when the selection is selected in the drop-down list, but before any changes to the selection are made. This event is used to allow the user to reject a selection by calling event.preventDefault ()

whereas the change has:

change Fires when the selection changes.

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

+108
Sep 04 '13 at 13:30
source share

Some changes were made to the select2 event names (I think on version 4 and later), so '-' will be changed to this ':' .
See the following examples:

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

You can check all events on the site "select2": select2 Events

+11
Apr 10 '16 at 19:17
source share

This works for me:

 $('#yourselect').on("change", function(e) { // what you would like to happen }); 
+2
Sep 15 '17 at 14:12
source share



All Articles