Exploring the world with Select2 world_countries search feature

I successfully integrated the world countries list from https://github.com/stefangabos/world_countries into select2 to display all countries. Does anyone have any insights on how to enable searching within the listed countries?

var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json';

$('select').select2({
  ajax: {
    url: countriesList,
    dataType: 'json',
    delay: 250,
    data: function (params) {
      console.log(params.term);
      return {
        q: params.term
      };
    },
    processResults: function (data) {
      return {
        results: $.map(data, function (item) {
          return {
            id: item.id,
            text: item.name
          };
        })
      };
    }
  },
  width: 300,
  dropdownAutoWidth: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4c5a535a5c4b0d7f0b110e110f125d5a4b5e110e">[email protected]</a>/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d4e5851585e490f7d09130c130d105f58495c130c">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet"/>

<select></select>

Answer №1

Since your data source is a JSON file, passing a search term to the URL will not affect the response. In this scenario, you can load the file once and then initialize select2 with the response:

var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json';

$.ajax({
    type: 'GET',
    url: countriesList,
    dataType: 'json',
    success: function(response) {
        $('select').select2({
          data: response.map(e => ({
            id: e.id,
            text: e.name
          })),
          width: 300,
          dropdownAutoWidth: true
        });
    },
    error: function() {},
    complete: function() {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f6e0e9e0e6f1b7c5b1abb4abb5a8e7e0f1e4abb4">[email protected]</a>/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7605131a131502443642584758465b141302175847">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet"/>

<select></select>

If you still prefer to use select2 with AJAX, you can filter the response based on the search term in processResults (although it's not recommended):

var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json';

$('select').select2({
  ajax: {
    url: countriesList,
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term
      };
    },
    processResults: function (data) {
      let term = this.container.results.lastParams.term;
      if (term) data = data.filter(d => d.name.includes(term));
      return {
        results: $.map(data, function (item) {
          return {
            id: item.id,
            text: item.name
          };
        })
      };
    }
  },
  width: 300,
  dropdownAutoWidth: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88b9d949d9b8ccab8ccd6c9d6c8d59a9d8c99d6c9">[email protected]</a>/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="592a3c353c3a2d6b196d77687769743b3c2d387768">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet"/>

<select></select>

Answer №2

Customizing the AJAX solution by adapting @Cuong-le-ngoc's code to handle case sensitivity.

var countriesList = 'https://cdn.jsdelivr.net/npm/world_countries_lists@latest/data/en/countries.json';

$('select').select2({
  ajax: {
    url: countriesList,
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term
      };
    },
    processResults: function (data) {
      let term = this.container.results.lastParams.term; 
      if (term) data = data.filter(country => (country.name.search(new RegExp(term, "i")) != -1 ));

      return {
        results: $.map(data, function (item) {
          return {
            id: item.id,
            text: item.name
          };
        })
      };
    }
  },
  width: 300,
  dropdownAutoWidth: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83f0e6efe6e0f7b1c3b7adb2adb3aee1e6f7e2adb2">[email protected]</a>/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b687e777e786f295b2f352a352b36797e6f7a352a">[email protected]</a>/dist/css/select2.min.css" rel="stylesheet"/>

<select></select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Items added to a form using jQuery will not be submitted when the form is posted

Issues with posting data from dynamically appended options in a form select using jQuery have been noticed. When an appended option is selected and the form is submitted, the value does not get posted (in this case, in an email template). Adding another no ...

Hiding a Blogger section when its widget is not visible

Take a look at this code: <b:section id='page-list'> <b:widget id='PageList1' locked='false' type='PageList' version='2' visible='true'> </b:widget> </b:section> I wa ...

Retrieving data with long parameters from a WebAPI GET request

Whenever I make a GET request to WebAPI using AJAX, I keep getting a 400 - Bad Request error. I have come to understand that this happens because the URL I am using is too long; the parameter I need to pass looks something like this: 1739;1591;2021;747 ...

What sets apart `this.user.id` from `this.user = {id: ....}`?

I am puzzled by the error thrown in the code below: import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-user', templateUrl: './user.compone ...

Is it possible for an independent perl script to execute a function from a website's javascript?

Looking at this complex setup, I find myself in a situation where I must find a way to trigger the $.ajax function on a webpage using a separate Perl script. The scenario involves a webpage making $.ajax calls to a Perl file, which retrieves data and send ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

How can we protect against CSRF attacks?

My typical approach involves using AJAX to input data into a MYSQL database like this: $.ajax({ url: "writescript.php", type: "POST", data: { data : mydata,//this could be anything }, success: function (html) { //do something ...

Error in HTML Sorting

I've been experimenting with some code from this fiddle: http://jsfiddle.net/kutyel/5wkvzbgt/ but when I copy it into Notepad++ and run it, it only displays: <html> Id: {{result.id}} Product: {{result.name}} Price: {{result.price | currency} ...

Utilizing ExtJS and its control feature

I am facing an issue with the following code block: run: function(e, row){ var me = this; var container = Ext.getCmp('centercontainer'); try { container.removeAll(); } catch(e) { } // The code snippet below is act ...

"Integrating JavaScript in C# Code Behind: A Step-by-Step Guide

Is there a way to trigger this javascript function using C# code in the backend when the page loads? Your assistance is greatly appreciated, thank you. <script type="text/javascript"> document.onkeydown = function (event) { event = ( ...

Tips for validating user input within a specific range in React?

I need to restrict user input in an input field to a number range defined by minimum and maximum values. I am working on this functionality using React/Next js. <Input value={tripCoverage} onChange={(e) => { const value = e.target.v ...

Leveraging .closest and .find for accessing values for manipulation

Hey there, thanks in advance for your help! I'm wondering if I'm on the right track by using .closest and .find to extract values from the input field .cab. The goal is to take those values and then show the appropriate door size in the DIV .cd ...

What could be causing me to receive a 401 error when making a Rails jQuery POST request?

I am currently utilizing devise within a rails application. I have successfully logged into my rails server (devise) using the following curl command: curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST h ...

The script is functional, however it is not compatible with node.js

Trying to implement a small Angular script on my .html page has been a bit challenging. The script runs perfectly when I load the page as a static file in the browser, but it fails to execute when I run my node.js app with a res.render statement that loads ...

The button that is disabled can still be triggered using the ".click()" function

When programmatically triggering a disabled button with an "onclick" function, the function is still fired. See example below: <div> <input type="button" onclick="save()" id="saveButton" value="save" disabled="disabled" /> <input ...

Explaining the functionality of jQuery validation code

While exploring online tutorials, I stumbled upon a fascinating guide that makes use of jQuery and a validation plugin to validate form input. You can view the live example here: http://jsfiddle.net/nK7Pw/. Everything seems to be working perfectly, but o ...

making a request using AJAX to retrieve an audio blob from an asynchronous API

I'm currently working with a legacy system and I am attempting to invoke an HTTP handler where I have implemented some logic to fetch an audio blob from an Azure service. However, I am facing difficulty in retrieving the content back to the client for ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

updating react state based on filtered redux properties

Just starting out with react & redux and running into some issues with filtering insights (articles, case studies, reports). My goal is to filter by industry, but I'm struggling to update the state with the filtered insights. InsightsPage.js con ...