Last updated: Mar 2, 2024
Reading time·2 min
The "$(...).select2 is not a function" jQuery error occurs for multiple reasons:
To solve the 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.
<!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 that's located in the index.js
file.
Here is the code in the index.js
file.
$(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 in which the scripts should be loaded:
index.js
).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.
You can check if you're loading the scripts correctly by opening your Developer
tools by pressing F12
and clicking on the Console
tab.
If you see any 404
errors related to loading the jQuery scripts, then the path
to the file is incorrect.
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.