countries DB logo

Documentation

Widgets

Plug-and-play widgets that inject country and subdivision data into your existing select elements

Widgets are JavaScript scripts that automatically populate your existing select elements with country and subdivision data. They work by detecting elements with specific CSS classes and injecting data via API calls, without modifying your styling or layout.

Widget Features

  • Automatic data injection into existing select elements
  • Multi-language support with automatic detection
  • Geolocation-based preselection
  • Real-time subdivision updates when country changes
  • Zero styling - fully customizable by you
  • Plug-and-play integration with any form
  • Works with your existing accessibility setup
  • Automatic language detection from browser settings

Widget Configuration

Configure individual widget behavior, styling, and data attributes for your select elements.

Basic Setup

Widgets work by adding CSS classes to your existing select elements. The widget script automatically detects these elements and injects country and subdivision data without modifying your styling or layout.

Requirements for API to Work:

This example uses the following configuration:

Required

1. Include the Widget Script

Add the JavaScript script with your valid public key: <script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

REQUIRED
All

2. Add CSS Class for Countries

Add class="country-selection" to your country select element.

REQUIRED
All

Recommended

3. Set Up Domains

Configure allowed domains in your dashboard for Start and Basic plans. Pro and Full plans have no domain restrictions.

RECOMMENDED
StartBasic

4. Set Up Languages

Configure available languages in your dashboard for Start and Basic plans. Pro and Full plans have all languages included.

RECOMMENDED
StartBasic

Example

Basic Widget Setup
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Add CSS classes to your existing select elements -->
<select class="country-selection"></select>

<!-- The widget will automatically populate this select -->

Live Example

Selected Value:

Country: Choose country

How it works:
  • This is the actual CountriesDB widget running live!
  • The widget script automatically populates this select element
  • The widget will automatically preselect the country based on your location
  • Select a country from the dropdown

Reload Option (reload: true)

When using client-side routing (React Router, Next.js, Vue Router, etc.), your page can change without a full refresh. The widget scans the DOM for .country-selection / .subdivision-selection during initialization, so on route navigation you should call CountriesWidgetLoad({ reload: true }) to re-scan and re-bind. This call should happen after you set window.CountriesDBConfig (typically in your route/page component).

Example

Reload the widget on route navigation
// app/countries/page.tsx (example)
useEffect(() => {
  const publicKey = process.env.NEXT_PUBLIC_COUNTRIESDB_PUBLIC_KEY

  // Where you set the widget config:
  ;(window as any).CountriesDBConfig = {
    publicKey,
  }

  // Then reload on route/page mount:
  if ((window as any).CountriesWidgetLoad) {
    ;(window as any).CountriesWidgetLoad({ reload: true })
  } else {
    import('@countriesdb/widget')
  }
}, [])

Adding Subdivisions (Optional)

Subdivisions are an optional feature that allows users to select states, provinces, or other administrative divisions within countries. The availability of subdivisions depends on your selected plan. They come in two forms: official ISO names and extended names to multiple languages, providing comprehensive coverage for international applications.

Requirements for API to Work:

This example uses the following configuration:

Required

1. Check Your Plan for Subdivisions

Subdivisions will only work if included in your plan. Check your dashboard for plan details and subdivision availability.

REQUIRED
BasicProFull

2. Add CSS Class for Subdivisions

Add class="subdivision-selection" to your subdivision select element.

REQUIRED
BasicProFull

3. Link Subdivisions to Countries

Use data-name="country_select_name" on country select and data-country="country_select_name" on subdivision select to link them together. You can name it however you like and have multiple country/subdivision pairs per form or page.

REQUIRED
BasicProFull

Example

Subdivision Setup
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country select with data-name -->
<select class="country-selection" data-name="country1"></select>

<!-- Subdivision select linked to country -->
<select class="subdivision-selection" data-country="country1"></select>

Live Example

Selected Values:

Country: Choose country

State/Province: Choose subdivision

Preselecting Countries and Subdivisions

Example

Preselect Country Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Preselect United States -->
<select class="country-selection" data-name="country_preset" data-preselected="US"></select>

<!-- Preselect California subdivision -->
<select class="subdivision-selection" data-country="country_preset" data-preselected="US-CA"></select>

Live Example

Selected Values:

Country: Choose country

State/Province: Choose subdivision

How it works:
  • Country is preselected to United States (US)
  • Subdivision is preselected to California (US-CA)
  • You can change the selections to see how it updates

Disabling Geolocation

By default, the widget automatically preselects the country based on the user's location. You can disable this behavior using data-preselected="" to show custom labels or when geolocation is not needed.

Example

Disable Geolocation Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Disable geolocation preselection -->
<select class="country-selection" data-name="country_no_geo" data-preselected=""></select>

<!-- Disable geolocation for subdivision -->
<select class="subdivision-selection" data-country="country_no_geo" data-preselected=""></select>

Live Example

Selected Values:

Country: Choose country

State/Province: Choose subdivision

How it works:
  • Geolocation is disabled using data-preselected=""
  • No automatic preselection based on location
  • Select elements show default empty state

Custom Labels with data-label

The data-label attribute allows you to customize the default option text in your select elements. This is useful for providing clear instructions to users about what they should select.

Example

Custom Label Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country select with custom label -->
<select
  class="country-selection"
  data-name="country_label"
  data-label="Choose your country"
  data-preselected=""></select>

<!-- Subdivision select with custom label -->
<select
  class="subdivision-selection"
  data-country="country_label"
  data-label="Select your state/province"
  data-preselected=""></select>

Live Example

Selected Values:

Country: Choose country

State/Province: Choose subdivision

How it works:
  • Notice the custom labels: "Choose your country" and "Select your state/province"
  • We disabled geolocation (using data-preselected="") to better show the custom labels

Custom Default Value with data-default-value

The data-default-value attribute allows you to customize the value of the default option in your select elements. By default, the widget uses an empty string ("") as the value for the default option. You can set this to any value you need for your form processing or validation logic.

Example

Custom Default Value Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country select with custom default value -->
<select
  class="country-selection"
  data-name="country_default"
  data-default-value="not_selected"
  data-preselected=""></select>

<!-- Subdivision select with custom default value -->
<select
  class="subdivision-selection"
  data-country="country_default"
  data-default-value="not_selected"
  data-preselected=""></select>

Live Example

Selected Values:

Country: not_selected

State/Province: not_selected

How it works:
  • Notice the default option has value not_selected instead of empty string
  • This custom value will be submitted with the form if no country/subdivision is selected
  • We disabled geolocation (using data-preselected="") to better show the custom default values

Standalone Subdivision with data-country-code

The data-country-code attribute allows subdivision selects to work independently by specifying the country directly. This is useful when you only need subdivision selection for a specific country, without requiring a separate country select element. The subdivision select will automatically load subdivisions for the specified country.

Example

Standalone Subdivision Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Standalone subdivision select for United States -->
<select class="subdivision-selection" 
        data-country-code="US"
        data-label="Select US state">
</select>

<!-- Standalone subdivision select for Canada -->
<select class="subdivision-selection" 
        data-country-code="CA"
        data-label="Select Canadian province">
</select>

Live Example

Selected Values:

US State: Select US state

Canadian Province: Select Canadian province

How it works:
  • Each subdivision select works independently using data-country-code
  • No country select is needed - the country is specified directly
  • US states load automatically for data-country-code="US"
  • Canadian provinces load automatically for data-country-code="CA"

Nested Subdivision Prefixes with data-nested1-prefix and data-nested2-prefix

The data-nested1-prefix and data-nested2-prefix attributes allow you to customize the visual indentation for different levels of nested subdivisions. This is useful for countries with multi-level administrative hierarchies where you want to visually distinguish between different subdivision levels (e.g., states/provinces vs counties/districts).

Example

Nested Prefix Example
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country select with France preselected -->
<select class="country-selection" 
        data-name="country_nested"
        data-preselected="FR">
</select>

<!-- Subdivision select with custom nested prefixes -->
<select class="subdivision-selection" 
        data-country="country_nested"
        data-nested1-prefix="โ†’ "
        data-nested2-prefix="โ†’โ†’ "
        data-label="Select French region/department">
</select>

Live Example

Selected Values:

Country: Choose country

Region/Department: Select French region/department

How it works:
  • France is preselected with data-preselected="FR" to show the nested structure immediately
  • Level 1 subdivisions (regions) have data-nested1-prefix="โ†’ " (single arrow)
  • Level 2 subdivisions (departments) have data-nested2-prefix="โ†’โ†’ " (double arrow)
  • This creates clear visual hierarchy: regions appear with "โ†’", departments with "โ†’โ†’"
  • You can customize the prefixes to use any characters: dashes, dots, bullets, etc.

Prefer Official Subdivisions with data-prefer-official

Add `data-prefer-official` to individual subdivision selects when you only want specific fields to use official ISO subdivisions instead of extended translations. This is useful when you want most selects to use extended data but specific fields to use official ISO data.

Official preference only takes effect when your plan has extended subdivisions available. If your plan only includes official subdivisions (or none), the flag is ignored and the appropriate default is used automatically.

Example

Using data-prefer-official
<!-- Country select -->
<select class="country-selection" data-name="country_official"></select>

<!-- Subdivision select with data-prefer-official -->
<!-- This will show official ISO subdivisions instead of extended -->
<select class="subdivision-selection" data-country="country_official" data-prefer-official></select>

<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

Live Example

Default (Extended if available)

Country: US

State/Province: โ€”

With data-prefer-official

Country: US

State/Province: โ€”

How it works:
  • Both selects are linked to the same country (United States)
  • The left select uses the default behavior (shows extended subdivisions if available in your plan)
  • The right select uses data-prefer-official to show official ISO subdivisions instead
  • This attribute only works when your plan includes extended subdivisions

Multi-select Countries and Subdivisions

Use the standard HTML multiple attribute on your select elements. The widget will populate options as usual and dispatch countriesWidget:update with detail.selectedValues as an array of selected codes. This works for both country and subdivision selects.

Example

Basic Multi-select
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country multi-select -->
<select class="country-selection" multiple data-name="country_multi"></select>

<!-- Subdivision multi-select (standalone US) -->
<select class="subdivision-selection" multiple data-country-code="US"></select>

Live Example

Selected Values:

Countries: (none)

US States: (none)

React to Changes with :update

Listen to the custom countriesWidget:update event to react to both user-initiated and widget-initiated changes (preselected, geoip, reload). The widget dispatches this event on the affected select element with useful detail like reason and type.

Example

Select with :update
<!-- Include the widget script -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<!-- Country & Subdivision selects -->
<select class="country-selection" data-name="country_change"></select>
<select class="subdivision-selection" data-country="country_change"></select>

<!-- Output -->
<div id="selection-output">Waiting for selections...</div>

<!-- :update handlers -->
<script>
  var countryEl = document.querySelector('select.country-selection[data-name="country_change"]');
  var subdivEl = document.querySelector('select.subdivision-selection[data-country="country_change"]');
  var outEl = document.getElementById('selection-output');

  function renderOutput(prefix, select) {
    if (!select || !select.value) return prefix + '(none)';
    var option = select.options[select.selectedIndex] || {};
    var text = option.text || '';
    return prefix + select.value + ' โ€” ' + text;
  }

  function updateOutput() {
    var countryText = renderOutput('Country: ', countryEl);
    var subdivText = renderOutput(' | Subdivision: ', subdivEl);
    outEl.textContent = countryText + subdivText;
  }

  function handleUpdate(event) {
    var t = event.target;
    if (t === countryEl) {
      // When country updates, only update the country part
      var countryText = renderOutput('Country: ', countryEl);
      // Preserve subdivision text if it exists
      var subdivText = renderOutput(' | Subdivision: ', subdivEl);
      outEl.textContent = countryText + subdivText;
    } else if (t === subdivEl) {
      // When subdivision updates, update both
      updateOutput();
    }
  }

  if (countryEl) countryEl.addEventListener('countriesWidget:update', handleUpdate, true);
  if (subdivEl) subdivEl.addEventListener('countriesWidget:update', handleUpdate, true);
</script>
Live Example

Ready Event (:ready)

countriesWidget:ready fires separately for every select. The country select dispatches its own ready event as soon as its options are available, and each subdivision select dispatches another ready event every time it finishes loading data (initial load + every reload triggered by a country change). Use this to wait for data before touching the DOM, then inspect event.detail (type, value, phase) to know which select finished.

Example

Wait for :ready before listening
<!-- Include the widget script with your public key -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY"></script>

<div class="form-group">
  <label for="ready-country">Country:</label>
  <select id="ready-country" class="country-selection" data-name="country_ready"></select>
</div>

<div class="form-group">
  <label for="ready-subdivision">Subdivision:</label>
  <select id="ready-subdivision" class="subdivision-selection" data-country="country_ready"></select>
</div>

<div class="output" id="ready-status">Waiting for widgetโ€ฆ</div>

<script>
  // Ready fires separately for each select: country fires once, subdivision fires on initial load + every reload
  var READY_EVENT = 'countriesWidget:ready';
  var statusEl = document.getElementById('ready-status');
  var events = [];

  function formatReady(detail) {
    var label = detail.type === 'country' ? 'Country select' : 'Subdivision select';
    return label + ' ready (' + detail.phase + ') โ€” current value: ' + (detail.value || '(none)');
  }

  document.addEventListener(READY_EVENT, function(event) {
    var detail = event.detail;
    // Filter to only our selects
    if (detail.name !== 'country_ready' && detail.country !== 'country_ready') {
      return;
    }

    // Add event to list (keep last 5 events)
    events.push(formatReady(detail));
    if (events.length > 5) {
      events.shift();
    }

    // Show all events, each on a new line
    statusEl.innerHTML = events.length > 0 ? events.join('<br>') : 'Waiting for widgetโ€ฆ';
  }, true);
</script>
Live Example

Global Configuration

These settings are applied to the entire widget script and affect all select elements on the page. Define them inside `window.CountriesDBConfig` before the widget loads (or pass them via script URL params when using the CDN).

Force Language with forced_language

By default, the widget displays country and subdivision names using the user's browser language (Accept-Language). You can override this globally by adding `forced_language` to the script URL or setting `forcedLanguage` in `window.CountriesDBConfig`. Below we force Spanish (es) so all names are shown in Spanish regardless of the user's browser settings. If a translation is not available, the widget falls back to English.

Example

Force Language (Spanish)
<!-- Force Spanish for all country and subdivision names -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&forced_language=es"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_forced_es"></select>

<!-- Subdivision select linked to the above country -->
<select class="subdivision-selection" data-country="country_forced_es"></select>
Live Example

Default Language with default_language

The widget automatically uses the end user's browser language (Accept-Language). When a matching translation is not available, you can provide a fallback by adding `default_language` to the script URL or setting `defaultLanguage` in `window.CountriesDBConfig`. This value is used only when `forcedLanguage` is not set and when the browser language cannot be resolved to a supported translation. Subdivision names appear in the chosen language if available (official ISO and/or extended translations depending on your plan); otherwise they fall back to English.

Example

Set Default Language (French)
<!-- Prefer browser language; fall back to French when unavailable -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&default_language=fr"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_default_fr"></select>

<!-- Subdivision select linked to the above country -->
<select class="subdivision-selection" data-country="country_default_fr"></select>

Follow Upward Subdivisions with follow_upward

The `follow_upward` parameter enables automatic navigation up the subdivision hierarchy, but only for cases where a subdivision is also a country itself (like Guam, Puerto Rico, etc.). Add `follow_upward=1` to the script URL or set `followUpward: true` in `window.CountriesDBConfig`. When enabled, selecting such a subdivision will automatically change the country to the parent country of that subdivision. For example, selecting Guam from the subdivision dropdown will automatically change the country selection to United States. This is useful for applications that need to handle complex country-territory relationships where territories are both subdivisions and countries.

Multi-select compatibility and limitations
  • Single-select country + single-select subdivision: Fully supported. Selecting a subdivision that is also a country will automatically switch the country selection to the parent country.
  • Any multi-select scenario: Not supported. `follow_upward` is completely disabled if either the country or subdivision select has the multiple attribute. This is because:
  • It is unclear which of multiple selected subdivisions should trigger the switch
  • It is unclear what the target country should be when multiple countries are selected
  • The behavior would be ambiguous and potentially conflicting

API validation: When using the backend validation API with multiple countries (array input), the `follow_upward` parameter is automatically ignored, as it requires a single selection to determine parent-subdivision relationships.

Example

Follow Upward Subdivisions (Guam subdivision โ†’ US country)
<!-- Enable follow_upward to automatically switch to parent countries -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&follow_upward=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_upward"></select>

<!-- Subdivision select linked to the above country -->
<select class="subdivision-selection" data-country="country_upward"></select>
Live Example

Prefer Official Subdivisions

By default, when your plan includes extended subdivisions, the widget will show the extended translations (50+ languages). Add `prefer_official=1` to the script URL or set `preferOfficialSubdivisions: true` in `window.CountriesDBConfig` to globally prefer the official ISO list.

Official preference only takes effect when your plan has extended subdivisions available. If your plan only includes official subdivisions (or none), the flag is ignored and the appropriate default is used automatically.

Example

Global preference (official everywhere)
<!-- Force the widget to use official ISO subdivisions globally -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&prefer_official=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_official"></select>

<!-- Subdivision select automatically uses official ISO data -->
<select class="subdivision-selection" data-country="country_official"></select>
Live Example

Disable Subdivision Type with show_subdivision_type

The `show_subdivision_type` parameter controls whether subdivision types (like "State", "Province", "Region", etc.) are displayed in subdivision names. Add `show_subdivision_type=0` to the script URL or set `showSubdivisionType: false` in `window.CountriesDBConfig`. By default, this is enabled (true), showing names like "California (State)". When disabled (false), it shows only the subdivision name like "California". This is useful for applications that want cleaner subdivision names without type indicators.

Note: This parameter only works for Official ISO subdivisions. For extended subdivision translations, the type is always included in the translation itself.

Example

Disable Subdivision Type
<!-- Disable subdivision type display -->
<!-- Note: show_subdivision_type only works with official ISO subdivisions. If your plan includes extended subdivisions, prefer_official=1 is required -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&show_subdivision_type=0&prefer_official=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_no_type"></select>

<!-- Subdivision select (uses official ISO data due to prefer_official=1) -->
<select class="subdivision-selection" data-country="country_no_type"></select>
Live Example

Allow Parent Selection with allow_parent_selection

The `allow_parent_selection` parameter controls whether users can select parent subdivisions in multi-level subdivision hierarchies. Add `allow_parent_selection=1` to the script URL or set `allowParentSelection: true` in `window.CountriesDBConfig`. By default, this is disabled (false), meaning users can only select the most nested subdivisions (the most specific ones). When enabled (true), users can also select parent subdivisions, which are more general administrative levels.

Note: This parameter is particularly useful for countries with complex administrative hierarchies where you want to allow selection at different levels of specificity.

Example

Allow Parent Selection
<!-- Enable parent subdivision selection -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&allow_parent_selection=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_parent"></select>

<!-- Subdivision select - will allow selecting parent subdivisions -->
<select class="subdivision-selection" data-country="country_parent"></select>
Live Example

Auto Init with auto_init

The `auto_init` parameter controls when the widget automatically initializes and loads country/subdivision data. Add `auto_init=0` to the script URL or set `autoInit: false` in `window.CountriesDBConfig`. By default, this is enabled (true), meaning the widget loads immediately when the script is included. When disabled (false), you have full control over when to initialize the widget by calling `window.CountriesWidgetLoad()`, allowing you to delay loading until specific conditions are met (like user authentication, form validation, or other prerequisites).

Example

Delayed Auto Init
<!-- Disable auto initialization -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&auto_init=0"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_delayed"></select>

<!-- Subdivision select linked to the above country -->
<select class="subdivision-selection" data-country="country_delayed"></select>

<!-- Load script button to manually initialize -->
<button id="load-script-btn" type="button">LOAD SCRIPT</button>

<script>
document.getElementById('load-script-btn').addEventListener('click', function(e) {
  e.preventDefault();
  if (typeof window.CountriesWidgetLoad === 'function') {
    window.CountriesWidgetLoad().catch(console.error);
  }
});
</script>
Live Example

ISO Country Names with iso_country_names

Enable this option to display ISO short names for countries (e.g., "United States of America") instead of localized names (e.g., "Estados Unidos" in Spanish). Add `iso_country_names=1` to the script URL or set `isoCountryNames: true` in `window.CountriesDBConfig`. This only affects country fields; subdivision fields remain unchanged. Sorting uses the displayed names.

Example

Show ISO Short Names (e.g., United States of America)
<!-- Use ISO short names for country fields -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&iso_country_names=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_iso"></select>

<!-- Subdivision select linked to the above country (unchanged) -->
<select class="subdivision-selection" data-country="country_iso"></select>
Live Example

Subdivision Romanization Preference

Prefer specific romanization systems for official subdivisions. Provide a comma-separated list (e.g., "un,bgn"). When a preferred system is not available for a country, the widget falls back to the default official name.

Real example (Belarus): BY provides UN and GOST/UN variants for the same subdivisions. For example, BY-BR has "Bresckaja voblasฤ‡" (UN X/6 2012) and "Brestskaja oblast'" (GOST 1983 = UN V/18 1987). With "un" you will see the UN form; with "gost,un" the GOST form is preferred. Open the live example below and select Belarus to see the difference.

Supported Values

These values can be combined in a comma-separated list to set priority.

Values

bgnMatches BGN/PCGN family labels (e.g., "BGN/PCGN 1956")
pcgnAlso part of BGN/PCGN family; treated the same as bgn when present in list
unMatches UN family labels (e.g., "UN V/18 1987")
isoMatches ISO family labels (e.g., "ISO 843:1997", "ISO 11940-2:2007")
country-specificAny other family fragment (e.g., "elot", "gost", or national standard tags) can be added

You don't need to specify a default. If none of your listed systems are available, the default official name is used automatically.

Note: This option is ignored when extended subdivisions are active.

Example

Live example: UN vs BGN (Belarus)
<!-- Prefer UN, then BGN -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&subdivision_romanization_preference=un,bgn"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_rom"></select>

<!-- Subdivision select that must use official ISO data (set preferOfficialSubdivisions=true globally or add data-prefer-official) -->
<select class="subdivision-selection" data-country="country_rom" data-prefer-official></select>
Live Example

Prefer Local Variant

Display local variant names for official subdivisions when available. Local variants are alternative names that may be more familiar to users in certain regions or contexts.

Real example (Egypt): EG subdivisions have both official names and local variants. For example, "Al Qฤhirah" has the local variant "Cairo", "Al Iskandarฤซyah" has "Alexandria", and "Al Jฤซzah" has "Giza". When prefer_local_variant is enabled, the widget will display these familiar names instead of the official transliterated names.

This option works alongside romanization preference: romanization system is selected first, then local variant is preferred if available. If no local variant exists for the selected romanization system, the regular name is used. This option only applies to official subdivisions (is_extended = 0), not extended ones.

Note: This option is ignored when extended subdivisions are active.

Example

Live example: Local Variants (Egypt)
<!-- Enable local variant preference -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&prefer_local_variant=1"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_local"></select>

<!-- Subdivision select that must use official ISO data (set preferOfficialSubdivisions=true or add data-prefer-official) -->
<select class="subdivision-selection" data-country="country_local" data-prefer-official></select>
Live Example

Name Filter

Customize country and subdivision names on-the-fly using JavaScript callback functions. Name filters override all other name sources (romanization, local variant, language preferences), giving you complete control over displayed names.

Use separate filters for countries and subdivisions. Each filter receives the original name, language information from the server, and the full item object. For subdivisions, the filter also receives the country code extracted from the subdivision code.

When name filters are used, the widget automatically re-sorts the options using Unicode-aware, case-insensitive, accent-sensitive sorting based on the detected language from the server. This ensures proper sorting even after names are customized (e.g., "ฤ…" sorts after "a" but before "b").

Filter functions can return a custom name (string), use the original name (null/undefined), or completely remove the item from the list (false).

This is useful for:
  • Customizing names to match your application's terminology
  • Adding prefixes or suffixes to names
  • Implementing language-specific customizations
  • Creating custom abbreviations or short forms
  • Filtering out unwanted countries or subdivisions from the list

Filter Function Parameters

Both country and subdivision filters receive these parameters. The subdivision filter additionally receives countryCode (extracted from the subdivision code).

Parameters

codeCountry/subdivision code (e.g., "US" for countries, "EG-C" for subdivisions)
originalNameName from server (already processed by romanization/local variant)
languageLanguage selected by server
countryCodeCountry code extracted from subdivision code (subdivisions only)
itemFull object from API

Example

Basic Usage with Static Map
<!-- Define filter functions before loading widget -->
<script>
  // Country name filter
  window.myCountryFilter = function(code, originalName, language, item) {
    // Filter out certain countries
    if (code === 'CA' || code === 'GB') {
      return false; // Remove these countries from the list
    }
    
    // Custom name map
    const customNames = {
      'US': 'United States of America',
      'EG': 'Egypt'
    };
    
    // Return custom name if exists, otherwise use original
    return customNames[code] || originalName;
  };
  
  // Subdivision name filter
  window.mySubdivisionFilter = function(code, originalName, language, countryCode, item) {
    // Filter out certain subdivisions
    if (code === 'EG-GZ' || code === 'US-CA' || code === 'US-NY') {
      return false; // Remove these subdivisions from the list
    }
    
    // Custom name map (e.g., for Egypt)
    const customNames = {
      'EG-C': 'Cairo City',
      'EG-ALX': 'Alexandria City'
    };
    
    // Language-specific customization
    if (language === 'ar') {
      return originalName; // Use original for Arabic
    }
    
    return customNames[code] || originalName;
  };
</script>

<!-- Load widget with filters -->
<script src="https://unpkg.com/@countriesdb/widget@latest/dist/index.js?public_key=YOUR_PUBLIC_KEY&countryNameFilter=myCountryFilter&subdivisionNameFilter=mySubdivisionFilter"></script>

<!-- Country select -->
<select class="country-selection" data-name="country_custom"></select>

<!-- Subdivision select -->
<select class="subdivision-selection" data-country="country_custom"></select>
Live Example