Why does the select2-removing event not trigger in select2 with allowClear?
Asked Answered
B

6

7

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.

Bullivant answered 3/7, 2014 at 15:43 Comment(0)
K
6

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.

Kelwunn answered 3/7, 2014 at 15:48 Comment(0)
H
15

select2 v4.0.3

$('#smartsearch').on('select2:unselecting', function (e) {
    alert('You clicked on X');
});

For all the select2 Options & Events

Hurricane answered 20/1, 2017 at 11:1 Comment(1)
As an addendum, unselecting fires before selection is removed, unselect whenever it is removed.Bullivant
J
10

For me the only thing that worked is the 'select2:unselect' event... (In non-multiple select box)

Judkins answered 11/4, 2015 at 22:6 Comment(0)
B
6

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.

Bullivant answered 3/7, 2014 at 15:43 Comment(1)
@Jatt.net Nope. I did not. But once I did I figured, what the hell, I might just add a question on so to ease my pain ;)Bullivant
K
6

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.

Kelwunn answered 3/7, 2014 at 15:48 Comment(0)
D
6

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;           
    });
Doggery answered 6/3, 2018 at 23:14 Comment(0)
S
2

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)

Scrotum answered 21/2, 2019 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.