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" 
        }
]
The Markup
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

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

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

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

The Script

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.

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

        // SELECT change EVENT TO READ SELECTED VALUE FROM DROPDOWN LIST.
        $('#sel').change(function () {
            $('p').text('Selected Item: ' + this.options[this.selectedIndex].text);
        });
    });
</script>

Try it yourself

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

Related Posts:

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