0
votes

I'm trying to make input for tags using jQuery Select2.

It works well by adding {tags: true} option to Select2, allowing user to add custom tags. But I don't want the dropdown to be displayed, so I added CSS:

  .select2-dropdown--below {
    display: none;
  }

Turns out, it still have unwanted behaviour when I enter new tag and press enter:

  • If I enter a new keyword, it inserted successfully
  • If I enter a keyword that is a substring from one of pre-selected options -- like "raw" or "berry" that already contained by "Strawberry" -- it won't insert

I think this is caused by Select2 behaviour that automatically highlights / select option that matches input string

How can I fix this? Or is there any way to properly remove Select2 dropdown?

Here is the full snippet:

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></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>
      <style>
      .select2-dropdown--below {
          display: none;
      }
      </style>
  </head>
  <body>
  <select multiple style="width: 100%">
      <option selected>Banana</option>
      <option selected>Orange</option>
      <option selected>Strawberry</option>
  </select>
  <script>
    $(document).ready(function () {
      $('select').select2({
        tags: true,
        width: 'resolve'
      });
    });
  </script>
  </body>
</html>
1

1 Answers

0
votes

Found the solution, I added a matcher to the option that always return null so it will not match and highlight any of pre-selected options

$('select').select2({
    tags: true,
    width: 'resolve',
    matcher: function () { return null; }
});