Advertisement
EricPy

SELECT2 Countries List

Mar 28th, 2020
1,089
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // THIS FUNCTION FETCHES COUTRIES LIST FROM API
  2. // I am using this part of select2 (https://select2.org/data-sources/ajax)
  3. $("#country").select2({
  4.   ajax: {
  5.     url: "https://restcountries.eu/rest/v2/name/",
  6.     dataType: 'json',
  7.     delay: 150,
  8.     data: function (params) {
  9.       return {
  10.         // probably this is the part I should change but I have no clue
  11.         q = params.term, // search term
  12.       };
  13.     },
  14.     processResults: function (data, params) {
  15.       // parse the results into the format expected by Select2
  16.       // since we are using custom formatting functions we do not need to
  17.       // alter the remote JSON data, except to indicate that infinite
  18.  
  19.       return {
  20.         results: data.items,
  21.       };
  22.     },
  23.     cache: true
  24.   },
  25.   placeholder: 'Select Country',
  26.   minimumInputLength: 1,
  27.   templateResult: formatCountry,
  28.   templateSelection: formatCountrySelection
  29. });
  30.  
  31. function formatCountry (country) {
  32.   if (country.loading) {
  33.     return country.text;
  34.   }
  35.  
  36.   var $container = $(
  37.     "<div class='select2-result-country clearfix'>" +
  38.       "<div class='select2-result-country__avatar'><img src='" + country.flag + "' /></div>" +
  39.         "<div class='select2-result-country__title'></div>" +
  40.     "</div>"
  41.   );
  42.  
  43.   $container.find(".select2-result-country__title").text(country.name);
  44.  
  45.   return $container;
  46. }
  47.  
  48. function formatCountrySelection (country) {
  49.   return country.name || country.text;
  50. }
  51.  
  52. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement