how to create dropdown list plugin using jquery

Updated : Nov 26, 2019 in Articles

how to create dropdown list plugin using jquery

In this article, we will learn about how to create dropdown list plugin using jquery dynamically

Create  a js file in your project add the given below  Snippet code

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

Create HTML page in your root director add the given below HTML code

<!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">load</button>
</body>
</html>
<script type="text/javascript">
$(document).ready(function () {
var data = [];
for (var i = 0; i < 20; i++) {
data.push({
id: i,
name: "tutprials helper" + i
});
}
$("#btnload").click(function () {
$("#cbodata").DropDowanPlugin({
list: data,
Optionsvalues: "id",
Textvalue: "name"
});
});

});
</script>

try to run your HTML page  Application

create dropdown list using jquery
create dropdown list using jquery