Fire callback when selection was made with select2 4.0, and retrieve the value of last selection

亡梦爱人 提交于 2019-12-11 02:31:35

问题


I am using the latest version of Select2 (4.0), and can't find out how to fire an event when a selection was made, AND retrieve the last selected value(when working with select boxes where multiple selections is possible).

In older versions of Select2, if I remember correctly, the "onchange" event of the select to which the plugin was attached fired when a selection was made, this doesn't work at the momment.

I've managed to fire a javascript function when the select boxes selection changes, but can't figure out the last selected id yet. Here's how I did it:

jQuery("#select2_holder").on("change", function(e) { 
        console.log(arguments);
});

I've also tried logging the arguments, but I can't find the desired information there either.

I've read through the documentation on the official website, but I can't find anything about callback functions in it.

Is there someone here who could point me in the right direction?

Thank you!


回答1:


Select2 provides the select2:select event which is triggered any time a new value is selected. For a single select, this is equivalent to change with some extra metadata included.

You can get the selected data object using evt.data where evt is the first argument passed into the event handler.

jQuery("#select2_holder").on("select2:select", function (evt) {
  console.log(evt.data);
});

You can find a live example of the events in the Select2 examples.


In older versions of Select2, if I remember correctly, the "onchange" event of the select to which the plugin was attached fired when a selection was made, this doesn't work at the momment.

This is correct, in Select2 3.x we used to modify the standard change event and put a few extra attributes on it. Since this was (unfortunately) never consistent, and it caused problems when people wanted to trigger change manually, we are not modifying the standard change event in Select2 4.0.




回答2:


Prev example is good, but 1 mistake : need use select2:selecting instead of select2:select

So we have

jQuery("#select2_holder").on("select2:selecting", function (evt) {
  console.log(evt);
});


来源:https://stackoverflow.com/questions/29376121/fire-callback-when-selection-was-made-with-select2-4-0-and-retrieve-the-value-o

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