select option generate value from ajax on change

select option generate value from ajax on change

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Cascading Dropdowns: Fetching City Data Automatically on Continent Change

Building cascading dropdown menus—where selecting a continent filters countries, and selecting a country filters cities—is a classic frontend pattern. While the basic logic of chaining AJAX requests works, developers often encounter specific UX requirements that break standard implementations. One such requirement is automatically populating the city list not just when a user selects a country, but also when the initial country load completes after a continent selection.

In your current setup, you have three jQuery handlers: one for the continent change event and one for the country change event. The core issue lies in the order of execution within your success callback for the continent request. You are clearing the city list ($(city).empty()) inside the continent AJAX success function, but you are not repopulating it immediately with the cities corresponding to the first available country.

To achieve this "fancy" behavior, you must ensure that whenever the country dropdown is populated, the city dropdown is simultaneously populated based on the currently selected country. If the user hasn't manually selected a specific country yet, you should default to the first item in the returned list. This prevents a state where the city dropdown remains empty or shows stale data while the user is navigating the initial load.

Implementing Automatic City Population

The solution requires modifying your existing continent AJAX success handler. Instead of simply appending options to the country select, you need to trigger the logic that populates the city select immediately after rendering the countries.

Here is how you can refactor the logic:

$('.continentname').change(function() {
    var selectedElement = $(this).find(':selected')[0];
    var continentId = selectedElement ? selectedElement.id : null; // Ensure ID is captured correctly
    
    $.ajax({
        type: 'POST',
        url: '../include/continent.php',
        data: { id: continentId },
        success: function(data) {
            var countrySelect = document.getElementById('country');
            var citySelect = document.getElementById('city');

            // Clear existing options
            $(countrySelect).empty();
            $(citySelect).empty();

            if (data.length > 0) {
                var countries = [];
                
                // Build the country list first
                for (var i = 0; i < data.length; i++) {
                    var optionId = data[i].sysid;
                    var cityName = data[i].name;
                    
                    // Assuming your backend returns cities associated with each country entry
                    // If the backend returns a flat list, you might need to group them or query per country.
                    // For this example, assume data[i] contains the immediate next level or we select the first.
                    
                    var optionHtml = '<option id="' + optionId + '" value="' + cityName + '">' + cityName + '</option>';
                    $(countrySelect).append(optionHtml);

                    // LOGIC CHANGE: Populate cities for the FIRST selected country immediately
                    // This assumes you have a function or logic to fetch cities for a specific country ID
                    if (i === 0) {
                        var firstCountryId = data[i].sysid; 
                        // Trigger country change event programmatically with the first item selected
                        $(countrySelect).val(firstCountryId); 
                        
                        // Now trigger the country handler to populate cities
                        $('.countryname').trigger('change');
                    }
                }
            }
        }
    });
});

The Necessity of a Second Request or Data Structure

You asked if you need to add another AJAX request inside the continent request. Technically, yes, if your continent.php only returns countries and not their associated cities in a nested structure.

If your backend (continent.php) returns a flat array of countries without city data, you have two architectural choices:

  1. Nested Response: Modify your backend to return an object where each country contains an array of its cities (e.g., { countries: [{ name: 'USA', id: '1', cities: ['New York', 'LA'] }] }). This eliminates the need for a third AJAX call and is generally more performant.
  2. Chained Requests: Keep your current backend structure but accept that you are initiating two asynchronous calls in quick succession (one to get countries, one to get cities). While feasible, this adds latency.

Your current code attempts to use a nested loop or logic that isn't fully realized. You cannot easily nest an AJAX call inside the success function of another if you want immediate UI feedback without potentially hitting rate limits or causing race conditions. However, triggering the .change() event on the country select after programmatically setting its value is the standard way to reuse your existing countryname handler without duplicating code.

Handling Programmatic Value Changes

Your source material shows this pattern:

$("#continent").val(continentid);
$("#continent").change();
$("#country").change(); // Note: This line is problematic if country hasn't been populated yet

In jQuery, calling .change() without first setting a valid value or handling the event manually can lead to undefined behavior if the target element is empty. A safer approach involves explicitly selecting the first country after the AJAX response and then triggering the change event on that specific element:

// Inside the continent success callback
var firstCountry = $(countrySelect).find('option').first();
if (firstCountry.length) {
    $(countrySelect).val(firstCountry.val());
    $(countrySelect).trigger('change');
}

This ensures that your countryname change handler fires, which in turn fetches the cities for that specific country and populates the city dropdown. This maintains a consistent flow where every user action (or automated system action) results in a predictable state update.

Our network