How to Integrate Select2 for Dropdown or Select Box?

Using Select2 from a CDN

A CDN (content delivery network) is the fastest way to get up and running with Select2!

Select2 is hosted on both the cdnjs and jsDelivr CDNs. Simply include the following lines of code in the section of your page:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

Or, You Can Download the Library Files From directly SELECT2 Github https://github.com/select2/select2

The precompiled distribution files will be available in vendor/select2/dist/css/ and vendor/select2/dist/js/, relative to your project directory. Include them in your page:

<link href="vendor/select2/dist/css/select2.min.css" rel="stylesheet" />

<script src="vendor/select2/dist/js/select2.min.js"></script>

Example: Single Select

<select class="js-example-basic-single" name="state">
  <option value="AL">Alabama</option>
    ...
  <option value="WY">Wyoming</option>
</select>

Select2 will register itself as a jQuery function if you use any of the distribution builds, so you can call .select2() on any jQuery selector where you would like to initialize Select2.

// In your Javascript (external .js resource or <script> tag)
$(document).ready(function() {
    $('.js-example-basic-single').select2();
});

Example: Multi-select boxes


Select2 also supports multi-value select boxes. The select below is declared with the multiple attribute.

The HTML Content is Like,

<select class="js-example-basic-multiple" name="states[]" multiple="multiple">
  <option value="AL">Alabama</option>
    ...
  <option value="WY">Wyoming</option>
</select>

The Script Content within Script Tag

$(document).ready(function() {
    $('.js-example-basic-multiple').select2();
});

For DEMO Examples, Please Visit:

https://select2.github.io/select2-bootstrap-theme/4.0.3.html

sources: https://select2.org/

Leave a Comment