Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
create new elements immediately in select2

I have a select2 that takes a few items, but I want to do a sort of slow loading of more items, by clicking the plus button. When the user hits the plus button, it will perform a new ajax that will add more options to select2. But the problem is that I haven't found any way to add new items to the select while it's open. I left as an example the append using an option.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.6/select2-bootstrap.min.css" rel="stylesheet" />
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select id="select-test" style="width: 300px"></select>
var formatTemplate, url = 'https://620aa88092946600171c5bf0.mockapi.io/test/v1/a';

formatTemplate = function(item) {
  var $state;

  if (item.id === 3) {
    $state = $('<span>Text: ' + item.text + '<button>+</button>' + '</span>');
  } else {
    $state = $('<span>Text: ' + item.text + '</span>');
  }

  return $state;
};

$('#select-test').select2({
  ajax: {
    url: url,
    type: 'GET',
    dataType: 'json',
    processResults: function(results) {
      return {
        results: results
      }
    },
  },
  templateResult: formatTemplate
});

async function asyncCheck() {
  await new Promise((resolve, reject) => {
    setTimeout(function() {
      $('li').on('mouseup', function(event) {
        var $button = $(this).find('button');

        if (event.target === $button[0]) {
          var newOption = new Option('Text: New', 9, false, false);

          event.stopPropagation();

          $('#select-test').append(newOption);
        }
      });

      $('.select2-dropdown--below').css('display', '');

      resolve();
    }, 700);
  });
}

$('#select-test').on('select2:open', function() {
  $('.select2-dropdown--below').css('display', 'none');
  asyncCheck();
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!