How to capture event when allowClear option of select2 is chosen?
Asked Answered
H

4

13

I've tried to capture select2:clearing event

$("#my-select").on("select2:clearing", function (e) {
    console.log('cleared');
});

(jsfiddle)

but it is not fired. I've also tried other versions (like select2:removed etc., see another question with similar problem), but it also doesn't work.

I use select2 4.0.0-beta2.

Himation answered 21/1, 2015 at 11:0 Comment(2)
Never used this library, but in the docs a dash is used in the event names instead of a colon, e.g. select2-clearingThermosphere
@MarioA, I've tried dashes, but the current doc (see select2.github.io/examples.html, Events section) says about colon.Himation
T
18

The changelog of select2 4.0.0-beta2 states:

Removed events

select2-clearing - Use select2:unselecting instead

https://github.com/select2/select2/releases

Thermosphere answered 21/1, 2015 at 11:37 Comment(4)
strange.The event select2:selecting is working, see: jsfiddle.net/1vgLnjbb/1Thermosphere
I assume that this is an error in the beta version. You should submit a bugreport on githubThermosphere
You are right, Mario - github.com/select2/select2/issues/2954. Thanks for your help.Himation
"select2:unselecting Triggered before a selection is removed. This event can be prevented." but console.log($select.select2('data')) on this event returns an empty arrayGrantgranta
H
19

This works:

$("#my-select").on("select2:unselecting", function(e) {

 });
Hel answered 18/9, 2018 at 2:26 Comment(0)
T
18

The changelog of select2 4.0.0-beta2 states:

Removed events

select2-clearing - Use select2:unselecting instead

https://github.com/select2/select2/releases

Thermosphere answered 21/1, 2015 at 11:37 Comment(4)
strange.The event select2:selecting is working, see: jsfiddle.net/1vgLnjbb/1Thermosphere
I assume that this is an error in the beta version. You should submit a bugreport on githubThermosphere
You are right, Mario - github.com/select2/select2/issues/2954. Thanks for your help.Himation
"select2:unselecting Triggered before a selection is removed. This event can be prevented." but console.log($select.select2('data')) on this event returns an empty arrayGrantgranta
B
2
$("#my-select").on("select2:select select2:unselecting", function(e) {
   //do something here
 });
Backwoodsman answered 11/1, 2018 at 8:34 Comment(0)
D
0

According to the select2 event documentations, all of the unselect, unselecting, clear and clearing events will works !

But consider that usnselect or unselecting events should be used by single selection mode, and clear or clearing should be used by multi selection mode. So the clear or clearing will fires if all of selected items cleared or clearing.

The differences between unselect and unselecting, is that unselecting fires before removing selection so you can prevented it.

Hope that it helps.

Disburden answered 24/1, 2020 at 21:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.