On Change Input Select Fetch All Country States Using jQuery Ajax

Input select already has a list of all countries within <option> tags. I used a free API to fetch all states. You can also fetch different info according to the countries.

//Fetch all country states
$('select#shippingCountry').change(function () { //I've a input select field with the ID of shippingCountry
    let country_code = $(this).val();
    $.ajax({
        url: "https://countriesnow.space/api/v0.1/countries/states",
        context: document.body
    }).done(function (data) {

        $(data.data).each(function () {
            if (this.iso3 == country_code) {
                $('select#check-state').html('<option value="" disabled="" selected="">State</option>');
                $(this.states).each(function () {
                    $('select#check-state').append('<option value="' + this.name + '">' + this.name + '</option>');
                });

            }

        });
    });
});

Leave a Comment

Your email address will not be published. Required fields are marked *