Dynamically Bind or Populate SELECT Dropdown List with JSON Data using jQuery Ajax

← PrevNext →

I am assuming you have read my previous article on How to read a JSON file, push the values in an array, and convert the array into an HTML table using jQuery. In that post I have explained about jQuery .getJSON() Method. I am using the same method here in this post explaining how to extract JSON data from an external file and bind or populate the data to a SELECT element using jQuery.

With an external file, I mean a .json file, stored locally or in a remote server.

👉 Now if you want you can also convert JSON data dynamically to an HTML table using Plain old JavaScript
Convert JSON to HTML table using JavaScript

The JSON

Open a NotePad and save the file with a name sample.json. Add below data to the file and save it.

[
    {
        "ID": "001",
        "Name": "Eurasian Collared-Dove" 
        },
    {
        "ID": "002",
        "Name": "Bald Eagle" 
        },
    {
        "ID": "003",
        "Name": "Cooper's Hawk" 
        },
    {
        "ID": "004",
        "Name": "Bell's Sparrow" 
        },
    {
        "ID": "005",
        "Name": "Mourning Dove" 
        }
]
The Code

I am using jQuery .getJSON() method to extract data from the JSON file. After extracting the data, I’ll iterate or loop through each requested JSON data and insert it into the SELECT element using jQuery append() method.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
    <p>
        <input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" />
    </p>

    <select id="sel">
        <option value="">-- Select --</option>
    </select>

    <p id="msg"></p>
</body>

<script>
    $(document).ready(function () {
        $('#bt').click(function () {
            
            var url = "https://www.encodedna.com/library/sample.json";

            $.getJSON(url, function (data) {
                $.each(data, function (index, value) {
                    // APPEND OR INSERT DATA TO SELECT ELEMENT.
                    $('#sel').append('<option value="' + value.ID + '">' + value.Name + '</option>');
                });
            });
        });

        // SHOW SELECTED VALUE.
        $('#sel').change(function () {
            $('#msg').text('Selected Item: ' + this.options[this.selectedIndex].text);
        });
    });
</script>
</html>
Try it

← PreviousNext →