Posts Learn Components Snippets Categories Tags Tools new About
/

How to Listen to Select2 event when selected

Learn the different types of select2 events and get to know the ways to listen the change event and it's values

Created on Nov 03, 2021

15 views

There are several types of events that select2 fire and depending on the event you can perform several actions. Imagine you want to notify a user with a toast notification after the select2 dropdown changes and that's totally possible if you are listening to the event. For this example let's say your select2 instance ID is "select2-input", to attach an event listener you can write your code like below.
$('#select2-input').on('change', function () {
  // show toast notification to user
});

All Select2 Events


Below are the available events that select2 provides and for each of these events you can listen and perform your action.
  • change - Triggered whenever an option is selected or removed.
  • change.select2 - Scoped version of change. See below for more details.
  • select2:closing - Triggered before the dropdown is closed. This event can be prevented.
  • select2:close - Triggered whenever the dropdown is closed. select2:closing is fired before this and can be prevented.
  • select2:opening - Triggered before the dropdown is opened. This event can be prevented.
  • select2:open - Triggered whenever the dropdown is opened. select2:opening is fired before this and can be prevented.
  • select2:selecting - Triggered before a result is selected. This event can be prevented.
  • select2:select - Triggered whenever a result is selected. select2:selecting is fired before this and can be prevented.
  • select2:unselecting - Triggered before a selection is removed. This event can be prevented.
  • select2:unselect - Triggered whenever a selection is removed. select2:unselecting is fired before this and can be prevented.
  • select2:clearing - Triggered before all selections are cleared. This event can be prevented.
  • select2:clear - Triggered whenever all selections are cleared. select2:clearing is fired before this and can be prevented.
Another example, do imagine that the user is clearing the select2 input, to call and fire off an action you can write your code like below. This is very handy when you want to update the backend status or some sort of backend process if it's necessary.
$('#select2-input').on('select2:clear', function (e) {
  // call ajax here
});
To get the params or the row that's being selected you can get it from the event parameter passed on as the 2nd function argument. In this case, you can use "e.params.data" to get the value of the selected option.
$('#select2-input').on('select2:select', function (e) {
  console.log(e.params.data)
  // filters.selectedReportType
});

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)