dynamically populate the dropdown from JSON schema using jquery

Updated : Nov 26, 2019 in Articles

dynamically populate the dropdown from JSON schema using jquery

In this article, we will discuss how to dynamically populate the dropdown from JSON schema using jquery

The given below example is helpful instead of implementing multiple functionalities for dropdowns we will use the only one javascript function

implementing the dynamically dropdown from JSON schema

first, you will create API that API should be returned dropdown values(value, text)

if you are using Asp.Net MVC following the given below Action method that method will return JSON data

[HttpGet]
public JsonResult getallemployees()
{
var lst = context.Customers.ToList().Select(x => new { x.Id, x.FirstName });
return Json(lst, JsonRequestBehavior.AllowGet);
}

The above JSON action result method we will call through ajax request then after inside the success we will bind that data to dropdown

before going to bind the data to dropdown we will Create an HTML page name like “DynamicDropDowan.html”

Add the given HTML page

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
    <script src="DropDowanList.js"></script>
</head>
<body>
    <select id="cbodata"></select>
    <button id="btnload">click </button>
</body>
</html>
<script type="text/javascript">
 $(document).ready(function () {
   // you will also pass restfull api here inted of calling controller
    dymanicdropdowan("../Home/getallemployees","cbodata");
 });
</script>

Go to your js root folder and add js file name like “DropDowanList.js”, see the given below implemented javascript code for dynamically populate the dropdown from JSON schema

the give below javascript file can have dymanicdropdowan(” your formed JSON data “, “your dropdown Id”) function this function where ever you want to populate the dynamic dropdown you will pass formed JSON data and dropdown id

(function ($) {
    $.fn.DropDowanPlugin = function (options) {
        var defaultsettings = $.extend({
            initialvalue: "Select Value",
            list: "",
            Optionsvalues: "",
            Textvalue: "",
        }, options)
        var selectedcombo = $(this);
        selectedcombo.find("option").remove();
        selectedcombo.append("<option value=0>" + 
defaultsettings.initialvalue + "</option>");
        var items = defaultsettings.list;
        if (defaultsettings.list == "") {
            items = [];
        };
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item[defaultsettings.Optionsvalues] != 0) {
                selectedcombo.append("<option value='" +
 item[defaultsettings.Optionsvalues] + "'>" +
 item[defaultsettings.Textvalue] + "</option>")
            }
        }
    }
}(jQuery));

function dymanicdropdowan(url, dropdowanid) {
    var url = url;
    window.dropdowanid = dropdowanid;
    $.ajax({
        url: url,
        data: {
            format: 'json'
        },
        error: function () {
            $('#info').html('<p>An error has occurred</p>');
        },
        dataType: 'json',
        success: function (data) {
            var col = [];
            window.cols = col;
            for (var i = 0; i < 1; i++) {
                for (var key in data[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }
            var hash = "#";
            var dropid = window.dropdowanid;
            var fullconcatstring = hash.concat(dropid);
            $(fullconcatstring).DropDowanPlugin({
                list: data,
                Optionsvalues: col[0],
                Textvalue: col[1],
            });
        }
    });
};

run your HTML page

output:

dynamically populate the dropdown from JSON schema
dynamically populate the dropdown from JSON schema

View Demo

Summary :

the above example we learned the basic concept of how to populate the dynamic dropdown for JSON schema using jquery next article we will see the same concept in angular js

if you want to run the above example you must and should be external jquery CDN required “jquery.min.js”

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>

thanks …