skip to Main Content

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/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/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?

2

Answers


  1. you should import jquery script first, then you can use select2.min.js.

    <html>
      <head>
    <linkhref="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.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>
      <script>
        $(document).ready(function () {
        $(".js-example-basic-multiple").select2();
        });
      </script>
    </html>
    
    Login or Signup to reply.
  2. 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/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search