Populate a SELECT Dropdown List with JSON Data using JavaScript

I am sharing two simple examples here in this post explaining how to populate a SELECT dropdown list with JSON data using JavaScript. In the first example, I’ll create a JSON array inside 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.

Must Read: How to Convert JSON Data Dynamically to an HTML Table using JavaScript

Bind SELECT Element with JSON Array using JavaScript

In my first, I’ll create a JSON array inside my 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.

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

<p id="msg"></p>
The Script
<script>
    window.onload = populateSelect();

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

        var ele = document.getElementById('sel');
        for (var 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.
        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 Yourself:




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

Extract Data from Local or External JSON File and Bind Data to <select> Element

The markup for this example remains the same as above.

The Script
window.onload = populateSelect();

function populateSelect() {

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

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

            var ele = document.getElementById('sel');
            for (var 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();
}

In this 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.

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

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);

Also Read: How to Add and Remove Multiple or Single SELECT Options using jQuery

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.

Previous - How to Auto Refresh Page Every 10 Seconds using JavaScript setInterval() Method



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner
Tweet this article Facebook Google+

Related Posts:

Join our Google Plus Community and be a part of a discussion!