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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> </head> <body> <div> <select style="width: 100%" class="selectmultiple" name="states[]" multiple="multiple"> </select> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <script> $(document).ready(function () { var apiUrl = 'https://jsonblob.com/api/category/f8be0591-a46e-11e7-86a2-d3ea1b9dd115'; $('.selectmultiple').select2(); $.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) .select2(); }); }); </script> </body> </html> |
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.