问题
I want to hook an event in my select2 once it gets cleared. The select2 was initalized with allowClear: true
. Yet the event
$select.on('select2-removed', function(event) {
console.log(event);
});
does not trigger when resetting the select2 with the clear button.
回答1:
According to the select2 source code, the clear
method use the event select2-clearing
instead of select2-removing
. So you should listen to this event too.
select2-clearing
and select2-removing
are triggered before the removal. select2-removed
is triggered after.
Keep in mind that clear
does not always trigger the select2-removed
event. It look like this event is triggered only if an element is actually removed from the input.
回答2:
select2 v4.0.3
$('#smartsearch').on('select2:unselecting', function (e) {
alert('You clicked on X');
});
For all the select2 Options & Events
回答3:
For me the only thing that worked is the 'select2:unselect'
event... (In non-multiple select box)
回答4:
I got it working with the 'select2-removed'
-event instead of 'select2-removing'
when using the clear button.
As to why it does not trigger still eludes me.
回答5:
I wanted to get data about the element just got removed on removed event. Following code worked for me;
$('#selector').on('select2:unselect', function (e) {
var data = e.params.data;
});
回答6:
If you are working with 4 or above version then use
$('#id').on('select2:unselecting', function (e) {
alert('You clicked on X');
});
Below 4 version
$('#id').on('select2-removing', function (e) {
alert('You clicked on X');
});
Make sure for 4 or above version it is select2:unselecting colon(:)
Less than 4 version it is select2-removing -(hyphen)
来源:https://stackoverflow.com/questions/24558101/why-does-the-select2-removing-event-not-trigger-in-select2-with-allowclear