Posted by Arjun on Wednesday 6th June 2018

Populate Select2 with AJAX data based on X event

select2 ajax load dependent dropdowns

In this post, I would like to show you data populating in select 2 dropdown based on x event and it will get data from the remote server using Http protocol, the same technique you can apply for dependent dropdowns to show data based on the selection.

Populate Select2 with AJAX data example

In the following exmple we are loading data on page load and appending data to select dropdown, same technique you can apply with any avaliable javascript events like click, change ..etc.

<!DOCTYPE html>
<html lang="en">
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <link href="" rel="stylesheet" />
         <select style="width: 100%" class="selectmultiple" name="states[]" multiple="multiple">
      <script src=""></script>
      <script src=""></script>
         $(document).ready(function () {
         var apiUrl = '';
         $.get(apiUrl, function (items) {
            var newOptions = '';
            for (var id in items) {
                newOptions += '<option value="' + id + '">' + items[id] + '</option>';
             $('.selectmultiple').select2('destroy').html(newOptions).prop("disabled", false)