In this article I will explain with an example, how to dynamically add (insert) Items (Options) to ASP.Net DropDownList on Button Click using JavaScript.
The Items (Options) Text and Value parts will be dynamically fetched from TextBoxes and then the Items (Options) will be added to ASP.Net DropDownList using plain JavaScript.
HTML Markup
The following HTML Markup consists of ASP.Net DropDownList, two HTML TextBoxes and a Button. The Button has been assigned a JavaScript Click event handler.
<asp:DropDownList ID = "ddlFruits" runat="server"></asp:DropDownList>
<hr />
Text: <input type="text" id = "txtText" />
Value: <input type="text" id = "txtValue" />
<input type="button" id = "btnAdd" value = "Add" onclick = "Add()" />
JavaScript function to add (insert) Items (Options) to ASP.Net DropDownList on Button Click
When the Button is clicked, the Add JavaScript function is called. Inside the JavaScript function, first the ASP.Net DropDownList is referenced and then an HTML Option element is created.
The Text part is set using the innerHTML property while the Value part is set using the value property of the HTML Option element.
Finally the HTML Option is added to the ASP.Net DropDownList.
<script type="text/javascript">
function Add() {
var ddl = document.getElementById("<%=ddlFruits.ClientID %>");
var option = document.createElement("OPTION");
option.innerHTML = document.getElementById("txtText").value;
option.value = document.getElementById("txtValue").value;
ddl.options.add(option);
}
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads