Skip to content
the poor coder

jquery select2 how to make dont close after select

Poor Man
Published
Reading time
1 min read
On this page

jQuery Select2: How to Make It Not Close After Select#

If you are using jQuery Select2 in your project, you might have come across a situation where you want the dropdown to stay open after the user selects an option. By default, Select2 closes the dropdown after an item is selected. However, there is a way to make it stay open.

Method 1: Using the CloseOnSelect Option#

Select2 provides an option called closeOnSelect that controls whether the dropdown should be closed after an item is selected. By default, this option is set to true, which means the dropdown will be closed after selection. To make it stay open, we need to set this option to false.

Here is an example code:

JavaScript

  $('#mySelect').select2({
    closeOnSelect: false
  });

In the above code, #mySelect is the ID of the select element for which we want to make the dropdown stay open.

Method 2: Using the Select2:open Event#

Another way to make the dropdown stay open is by using the select2:open event. This event is triggered when the dropdown is opened. We can use this event to prevent the dropdown from being closed after an item is selected.

Here is an example code:

JavaScript

  $('#mySelect').on('select2:open', function(event) {
    $('.select2-results__options').unbind('mousedown');
    $('.select2-results__options').on('mousedown', function(e) {
      e.stopPropagation();
    });
  });

In the above code, we are binding a mousedown event to the dropdown options and preventing the event from propagating further. This means that the dropdown will not close when the user clicks on an option.

These are the two ways to make the jQuery Select2 dropdown stay open after selection. Choose the one that suits your requirements the best.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC