2

Please tell me how to connect the select2 handler to new elements that are append or load.

$("body").append('<select class="js-example-basic-single"><option>1</option><option>2</option><option>3</option></select>');
$(".js-example-basic-single").select2();
$("body").append('<select class="js-example-basic-single"><option>4</option><option>5</option><option>6</option></select>');
select {
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.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>
<body>
</body>
Vans
  • 185
  • 1
  • 8
  • [tag:select2] must be attached after you append your html - move/copy your `$(".js-example-basic-single").select2();` to after the `.append` – freedomn-m Feb 24 '23 at 10:10
  • 1
    @freedomn-m I described that the script is loaded before the appearance of the elements – Vans Feb 24 '23 at 10:18
  • @freedomn-m Do you think I just placed the select2 function and adding elements? So it doesn't fit. First, the script is loaded, then elements are added without reloading online. – Vans Feb 24 '23 at 11:01
  • @freedomn-m Updated the code how it works. – Vans Feb 24 '23 at 11:05
  • `$(".js-example-basic-single")` is not "dynamic" - it only applies to the elements that exist at the time the code runs. So your (updated) code adds 1 `select` then `$(".js-example-basic-single").select2()` converts that select to select2. You then add a second select, but the `.select2()` code has already run, so doesn't then convert that new select. You need to call `.select2()` *after* you append new elements to the DOM. – freedomn-m Feb 24 '23 at 11:09
  • 1
    How can I bind the select2 function before the elements appear? – Vans Feb 24 '23 at 11:15
  • 1
    Right - no. you can't. You *could* use a MutationObserver, but might be overkill. See this question: https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – freedomn-m Feb 24 '23 at 11:19
  • @freedomn-m Can you provide an answer to close this question? – Vans Feb 24 '23 at 12:47
  • I would only close-vote it as a duplicate of: https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – freedomn-m Feb 24 '23 at 13:25

1 Answers1

0

You could use the MutationObserver and do something like the below which basically watches the document for ANY element changes.

const observer = new MutationObserver(() => {
  $(".js-example-basic-single").each(function() {
    const $this = $(this);

    // This checks if select2 has already be initialized
    // preventing an infinate loop
    if (!$this.data('select2')) {
      $this.select2();
    }
  });
});

observer.observe(document.documentElement, {
  subtree: true,
  childList: true
});
Levi Cole
  • 3,561
  • 1
  • 21
  • 36