Solve - $(...).select2 is not a function jQuery Error

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - $(...).select2 is not a function #

The "$(...).select2 is not a function" jQuery error occurs for multiple reasons:

  1. Forgetting to include the select2 library.
  2. Loading the select2 library before the jQuery library.
  3. Loading the jQuery library twice.
  4. Specifying an incorrect path to the jQuery files.

To solve the "$(...).select2 is not a function" jQuery error, make sure to load the jQuery library before loading the select2 library. The libraries have to be loaded only once on the page, otherwise the error is thrown.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <!-- ✅ Load CSS file for Select2 --> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <!-- ✅ load jQuery ✅ --> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> <!-- ✅ load JS for Select2 ✅ --> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer" ></script> </head> <body> <!-- 👇️ Select menu --> <select class="basic-single" name="state"> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> </select> <!-- ✅ Your JS script here ✅ --> <script src="index.js"></script> </body> </html>

Note that we loaded the JavaScript code for the select2 library after loading the jQuery library, but before running our code located in the index.js file.

Here is the code in the index.js file.

index.js
$(document).ready(function () { $('.basic-single').select2(); });

In the index.js file, we make sure the DOM is ready before initializing the Select2 menu. You only need a single $(document).ready() block per page.

If you load the page you will see the select menu.

The order of the scripts is very important because they rely on one another. Make sure to load the jQuery script first, then the Select2 script and lastly load your JS script.

If you still get the error you might be loading the jQuery library twice. Loading the library twice re-runs the initialization process and causes the error to be thrown.

If you are loading the libraries from files on your local file system, make sure to specify the paths to the files correctly. Specifying an incorrect path to a script is equivalent to not loading the script at all.

You can check if you're loading the scripts correctly when you open the console in your browser. If you see any 404 errors related to loading the jQuery scripts, then the path to the file is incorrect.

Use the search field on my Home Page to filter through my more than 1,000 articles.