javascripthtmljqueryjquery-select2cdn

How to get a simple multi-select box using Select2


I would like to use the select2 library in my html document because it has a pillbox style select control I'd like to use.

I followed the relevant Installation and Getting Started sections from the docs. I also loaded JQuery using a CDN link but as you can see below I'm getting an error:

$(document).ready(function() {
  $('.js-example-basic-multiple').select2();
});
<html>
  <head>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">             </script>
  </head>
  <body>
        <select class="js-example-basic-multiple" name="states[]" multiple="multiple">
        <option value="AL">Alabama</option>
        <option value="WY">Wyoming</option>
    </select>
  </body>
</html>

What am I missing here?


Solution

  • Importing the lib select2 before jquery causes the problem (that's because select2 needs jquery to work properly ),

    move the jquery script on top of the select2 script then it works correctly

    $(document).ready(function() {
      $('.js-example-basic-multiple').select2();
    });
    .js-example-basic-multiple {
      width:250px;
    }
    <html>
      <head>
        
        
      </head>
      <body>
            <select class="js-example-basic-multiple" name="states[]" multiple="multiple">
            <option value="AL">Alabama</option>
            <option value="WY">Wyoming</option>
        </select>
        
      </body>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js">             </script>
        <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    </html>