A simple tutorial contains JSON data from the rest API on the select2 plugin using jquery. Hi friends, it’s been a long time since I made a new article in the midst of my busy life as a programmer. In this article, I will share a few tricks on how to display JSON data in our favorite select plugin, select2. Check out the following tutorial.
Maybe a lot of select2 tutorials have been shared in various sites. There are still many who ask me how to add data or load JSON data to select2. The method is quite easy, please follow the steps below
Tutorial How To Load JSON Data To Select2 Plugin
In my example, I use css bootstrap framework.
Create select / combobox elements in html
1 2 3 4 5 6 7 8 | <div class="container"> <h1>Load JSON Data To Select2 JQuery Plugin</h1> <div class="row"> <div class="col"> <select class="select2"></select> </div> </div> </div> |
Add the following CSS so that the width of the select2 element can be maximum / 100%
1 2 3 4 5 6 | .select2-container{ width: 100%!important; } .select2-search--dropdown .select2-search__field { width: 98%; } |
The most important code is the following: JQuery code to load JSON data on select2
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 | $(document).ready(function(){ $.ajax({ url: "https://jsonplaceholder.typicode.com/users", type: "GET", success: function(data, textStatus, jqXHR) { var xdata = $.map(data, function (obj) { obj.text = obj.text || obj.name; return obj; }); $(".select2").select2({ placeholder: "test", data:xdata, }); }, error: function (request, textStatus, errorThrown) { swal("Error ", request.responseJSON.message, "error"); if(request.status == "401"){ alert("Unauthorized Access "); return false; } } }); }); |
The above method is quite short, and you can practice the application that you are developing.
I have another select2 tutorial “How To Use Select2 Remote AJAX With Example in JQuery, PHP And MySQL” maybe you can review it as learning material.
So, my short tutorial How to load JSON data to select2 with JQuery, I hope is useful.
Leave a Reply