DEV Community

Nathan Dauda
Nathan Dauda

Posted on

5

Populate html select fields with countries and states from api using jquery

This post shows you how to easily populate countries and their states in html select field using restful countries api and jquery.

I assume you already know the basics of Jquery so i won't be giving line by line code details. just copy and paste the code below in your html and you are good to go.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
        //Populate countries select on page load
        $(document).ready(function(){
            //Call restful countries country endpoint
            $.get('https://restfulcountries.com/api/v1/countries?fetch_type=slim',function(countries){

                //Loop through returned result and populate countries select
                $.each(countries.data,function(key,value){
                    $('#country-select')
                        .append($("<option></option>")
                            .attr("value", value.name)
                            .text(value.name));
                });
            });
        });

        //Function to fetch states
        function initStates(){
            //Get selected country name
            let country=$("#country-select").val();

            //Remove previous loaded states
            $('#state-select option:gt(0)').remove();
            $('#district-select option:gt(0)').remove();

            //Call restful countries states endpoint
            $.get('https://restfulcountries.com/api/v1/countries/'+country+'/states?fetch_type=slim',function(states){

                //Loop through returned result and populate states select
                $.each(states.data,function(key,value){
                    $('#state-select')
                        .append($("<option></option>")
                            .attr("value", value.name)
                            .text(value.name));
                });
            });
        }
    </script>
Enter fullscreen mode Exit fullscreen mode

Then finally add 2 select fields in your html form with IDs country-select and state-select which would be referenced in the script. The country select has an onchange event listener to populate the states based on the country selected.


<select onchange="initStates()" id="country-select" class="form-control">
    <option selected disabled>Country</option>
</select>

<select  id="state-select" name="" class="form-control">
    <option selected disabled>State</option>
</select>

Enter fullscreen mode Exit fullscreen mode

Notice the fetch_type=slim on the api call urls, That indicates an option to only fetch the country name flag and calling code, That's because restful countries api returns other details like presidents,covid 19, population and others. and you don't need all that to populate your select.

You can add your own styling like a preloader on the select while it loads data, or the selected countries flag display on the country select, you can get the flag url from the country result as value.href.flag .

If you want to explore restful countries for other use cases, you may visit the website https://restfulcountries.com/ or follow twitter page @restfulcountrie .

Thank you for viewing this post. lets connect on twitter @NateDauda

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay