In this article I will explain with an example, how to dynamically add (insert) Items (Options) to DropDownList i.e. HTML Select element on Button click using jQuery.
The Items (Options) Text and Value parts will be dynamically fetched from TextBoxes and then the Items (Options) will be added to HTML DropDownList using jQuery.
Add (Insert) Items (Options) to DropDownList on Button Click using jQuery
The following HTML Markup consists of an HTML DropDownList to which the Items (Options) will be dynamically added on Button click using jQuery.
It also contains two HTML TextBoxes and a HTML Button element. The two HTML TextBoxes will be used to capture the Text and Value parts of the HTML Select DropDownList while the HTML Button will be used for adding Items (Options) to the HTML DropDownList.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id = "ddlFruits"></select>
<hr />
Text: <input type="text" id = "txtText" />
Value: <input type="text" id = "txtValue" />
<input type="button" id = "btnAdd" value = "Add" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").click(function () {
var option = $("<option />");
option.html($("#txtText").val());
option.val($("#txtValue").val());
$("#ddlFruits").append(option);
});
});
</script>
</body>
</html>
Explanation:
When the Add button is clicked, the jQuery Click event handler is executed inside which first the HTML DropDownList is referenced and then an HTML Option element is created.
The Text part is set using the html() jQuery function while the Value part is set using the val() jQuery function of the HTML Option element.
Finally the HTML Option is added to the DropDownList.
Screenshot
Demo
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Downloads