Fill DropDownList from JSON Array using jQuery

In this post,we will learn about how to Fill DropDownList from JSON Array using jQuery with an example.

Description:

In my previous posts I have explained various topics like 10 Useful tools for web developers and designer,Anonymous Types In C# ,Sealed Class in C#, Continue keyword in C#.Net, Difference between string and StringBuilder in C#, Difference between a struct and a class in C#, Boxing & Unboxing in C# ,Dynamic Type In C#, Named Arguments In C#.

Now in this post, I will explain about how to Fill DropDownList from JSON Array using jQuery with appropriate example.



Here,TheĀ JSON Array will be read and parsed and then one by one the each JSON object from the JSON Array will be added as Items to the DropDownList jQuery using.

The following HTML Markup consists of an HTML DropDownList and a Button. When the Button is clicked, the JSON Array will be parsed and its items will be used to populate the HTML DropDownList.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <input type="button" id="btnGenerate" value="Populate DropDownList" onclick="FillDropDownList()" />
    <hr />
    <select id="ddlCustomers">
    </select>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function FillDropDownList() {
            //Build an array containing Customer records.
            var customers = [
                { EmployeeId: 1, EmployeeName: "Adam Perez", Country: "United States" },
                { EmployeeId: 2, EmployeeName: "Kit Ponting", Country: "Aus" },
                { EmployeeId: 3, EmployeeName: "Brett Lee", Country: "France" },
                { EmployeeId: 4, EmployeeName: "Shikhar Dhawan", Country: "India" }
            ];

            var ddlCustomers = $("#ddlCustomers");
            $(customers).each(function () {
                var option = $("<option />");

                //Set Customer EmployeeName in Text part.
                option.html(this.EmployeeName);

                //Set Customer EmployeeId in Value part.
                option.val(this.EmployeeId);

                //Add the Option element to DropDownList.
                ddlCustomers.append(option);
            });
        }
    </script>
</body>
</html>

Summary

You can also read about ASP.NET,C#.NET, JQUERY, AJAX.

I hope you get an idea about how to Fill DropDownList from JSON Array using jQuery.
I would like to have feedback for my blog.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website