Populate a SELECT dropdown list with JSON data using JavaScript

← PrevNext →

I am sharing two simple examples here explaining how to populate a SELECT dropdown list with JSON data using JavaScript. In the first example, I’ll create a JSON array using JavaScript and bind the data to a SELECT element. In the second example, I’ll extract data from an External JSON file using XMLHttpRequest Object, parse the JSON and bind the data to the SELECT element.
See this demo

🚀 Check whether your JSON dataset is valid or not and then proceed.

Bind SELECT Element with JSON Array using JavaScript

I’ll first create a JSON array inside a JavaScript function and add few data to it. Next, I’ll iterate (loop) through each value in the array and bind the values to the SELECT element.

Related Post: How to Convert JSON Data Dynamically to an HTML Table using JavaScript

The Markup and the Script
<html>
<head>
    <title>Bind SELECT Dropdown with JSON using JavaScript</title>
</head>
<body>
    <p>
        <input type="button" 
            onclick="populateSelect()" 
                value="Click to Populate SELECT with JSON" />
    </p>

    <!--The SELECT element.-->
    <select id="sel" onchange="show(this)">
        <option value="">-- Select --</option>
    </select>

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

<script>
    function populateSelect() {
        // THE JSON ARRAY.
        let birds = [
            {"ID": "001", "Bird_Name": "Eurasian Collared-Dove"},
            {"ID": "002", "Bird_Name": "Bald Eagle"},
            {"ID": "003", "Bird_Name": "Cooper's Hawk"},
        ];

        let ele = document.getElementById('sel');
        for (let i = 0; i < birds.length; i++) {
            // POPULATE SELECT ELEMENT WITH JSON.
            ele.innerHTML = ele.innerHTML +
                '<option value="' + birds[i]['ID'] + '">' + birds[i]['Bird_Name'] + '</option>';
        }
    }

    function show(ele) {
        // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
        let msg = document.getElementById('msg');
        msg.innerHTML = 'Selected Bird: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' +
            'ID: <b>' + ele.value + '</b>';
    }
</script>
</html>
Try it

See how I got the selected text of the SELECT element in the above example.

ele.options[ele.selectedIndex].text

Also Read: How to Use AngularJS ng-options to Bind or Populate JSON Array to a SELECT DropDownList

Fetch (or extract) Data from an external JSON File and Bind Data to <select> dropdown list

🚀 Do you know you can check weather a JSON is Valid or not with the click of a button? Check this out.

The markup for this example remains the same as above.

The Script
<body>
    <select id="sel" onchange="show(this)">
        <option value="">-- Select --</option>
    </select>

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

<script>
    window.onload = populateSelect();

    function populateSelect() {
        // CREATE AN XMLHttpRequest OBJECT, WITH GET METHOD.
        var xhr = new XMLHttpRequest(), 
            method = 'GET',
            overrideMimeType = 'application/json',
            url = '../../library/sample.json';        // ADD THE URL OF THE FILE.

        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                
                // PARSE JSON DATA.
                let birds = JSON.parse(xhr.responseText);

                let ele = document.getElementById('sel');
                for (let i = 0; i < birds.length; i++) {
                    // BIND DATA TO <select> ELEMENT.
                    ele.innerHTML = ele.innerHTML +
                        '<option value="' + birds[i].ID + '">' + birds[i].Name + '</option>';
                }
            }
        };
        xhr.open(method, url, true);
        xhr.send();
    }

    function show(ele) {
        // GET THE SELECTED VALUE FROM <select> ELEMENT AND SHOW IT.
        var msg = document.getElementById('msg');
        msg.innerHTML = 'Selected Bird: <b>' + ele.options[ele.selectedIndex].text + '</b> </br>' +
            'ID: <b>' + ele.value + '</b>';
    }
</script>
Try it

In the above example, I am using XMLHttpRequest() objects to connect with a JSON file.

XMLHttpRequest, provides the necessary methods and properties to interact with server objects, asynchronously. It is used extensively with Ajax applications.

By the way, there's another simple method in JavaScript that you can use to fetch data from external files. See this article. This method uses async and await. Its a must see article.

Note: Some old Internet Explorer versions do not support XMLHttpRequest objects.

👉 Do you know you can create a Cascading SELECT dropdown list using JSON data? See this post.
Cascading SELECT dropdown list using JSON data

Next, I am using the property onreadystatechange to execute a callback function. Since, its an asynchronous process, callback function is executed only when the file is fully loaded.

xhr.onreadystatechange = function () {
…
}

With this condition, if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200), I am checking if the request is successful. Check the two properties in your browser console.

console.log(xhr.readyState);
console.log(xhr.status);

You may also like: How to add/remove Multiple or Single SELECT options using a simple script.

After we have checking the state of the request, we’ll parse or extract data from JSON file using XMLHttpRequest’s responseText property.

var birds = JSON.parse(xhr.responseText);

The binding of JSON data to the <select> element is similar to the process I have explained the first example above.

Happy coding. 🙂

← PreviousNext →