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

I am sure you might 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 showing an example on how to extract JSON data from an external file and bind or populate the data to a SELECT element using jQuery.

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

Also Read: How to Convert JSON data Dynamically to an HTML Table using Plain JavaScript

The JSON File

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

[
    {
        "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" 
        }
]

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

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

Well, that’s it. Thanks for reading.

Previous - Binding Click Event to a Dynamically Created Element using jQueryNext - Using jQuery mousemove() Method to Capture Mouse Pointer location



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 Google+

Related Posts:

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