84

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
});
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
spyfx
  • 1,311
  • 4
  • 14
  • 24
  • 2
    You can bind to the 'change' event, there's a section called "Events" on the link you gave with a very long code snippet for all the different event bindings. – Ross Sep 04 '13 at 13:29

7 Answers7

179

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.

KyleMit
  • 30,350
  • 66
  • 462
  • 664
Ross
  • 3,022
  • 1
  • 17
  • 13
  • 14
    Events have other names in newer versions (eg 'select2:select'), see [https://select2.github.io/examples.html](https://select2.github.io/examples.html) – snakey Apr 22 '15 at 13:53
  • 1
    Events are [here](https://select2.github.io/examples.html#events) in the doc. Not obvious with the FAQ style. – Pierre de LESPINAY Aug 29 '16 at 12:58
  • 1
    the "selecting" call is done right before the value is set. which will lead to: "console.log($(this).val())" outputing a blank value – Joseph Groot Kormelink Jul 19 '18 at 13:32
  • When I tried same in my angular application, it was giving me wrong values. Suppose 4 values are there in select2 options. 1 Minute, 5 Minute, 1 Hour, Daily. Now using $('#yourselect').on("select2-selecting", function(e) {...} It was giving me previous value that what I have selected. – Yash Jain Aug 17 '18 at 04:52
  • Instead of that I tried $('#yourselect').on("select2-select"),function(e){...} That worked for me – Yash Jain Aug 17 '18 at 04:53
  • As "selecting" call is done right before the value is set, if someone needs the selected value, it needs to change the event to ```select2:select``` or ```select2-select``` instead of ```select2:selecting``` or ```select2-selecting``` – quasar May 05 '20 at 07:01
31

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

Tariq
  • 2,853
  • 3
  • 22
  • 29
14

It works for me:

$('#yourselect').on("change", function(e) { 
   // what you would like to happen
});
Roby Sottini
  • 2,117
  • 6
  • 48
  • 88
  • I don't understand why but this worked for me when Tarek's answer wouldn't. I've even got his answer to work in a separate project but for some reason this was the only override that got my project up and running. – tokyo0709 Dec 29 '17 at 16:33
  • @tokyo0709 It works because `.change` event comes later in the series of executions than `select2:select` event. For me I was trying to capture the select's css on `select2:select` but even though I saw it on inspector I couldn't capture it via `select2:select` - when I changed to `.change` it worked because Select2 fires `select2:select` event *before* updating the css for the orginal select .. a little crazy, in my opinion. – a20 Apr 21 '18 at 02:24
  • 1
    [@a20](https://stackoverflow.com/users/163382/a20) sometimes an easy workaround is setting the dom elements css via html css so you don't have to wait for the javascript engine to catch up. It works well in some instances. – yardpenalty.com Feb 28 '19 at 15:24
11

As per my usage above v.4 this gonna work

$('#selectID').on("select2:select", function(e) { 
    //var value = e.params.data;  Using {id,text format}
});

And for less then v.4 this gonna work:

$('#selectID').on("change", function(e) { 
   //var value = e.params.data; Using {id,text} format
});
amku91
  • 1,010
  • 11
  • 21
  • This is not worked for me. I have changed above code to as given below. `e.params.args.data` – Tushar Saxena Dec 27 '18 at 14:52
  • This didn't work for me either, e.params.data through data field not found for undefined. Upon closer inspection, there was no params field set for e. For my problem, I just needed to read the value so e.val was enough for me. – NemyaNation Apr 25 '20 at 17:58
  • @TusharSaxena e.params.args.data worked for me thank you – Sneha Jun 29 '22 at 08:07
5

For above v4

$('#yourselect').on("select2:select", function(e) { 
     // after selection of select2 
});
Shujat Munawar
  • 1,657
  • 19
  • 23
4

This worked for me (Select2 4.0.4):

$(document).on('change', 'select#your_id', function(e) {
    // your code
    console.log('this.value', this.value);
});
Pablo
  • 643
  • 9
  • 12
0
//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});