Add a new option for an asp:DropDownList from javascripts

With using pure javascripts, we can add a new option dynamically to a dropdown list. Below is an example I’ve created. I’m adding the option ‘Hi’ to the dropdown list on click of the Button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html>
    <script type="text/javascript">
        function addItem() {
            var option = document.createElement("option");
            option.text = "Hi";
            try {
                // for IE earlier than version 8
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, x.options[null]);
            catch (e) {
                document.getElementById("<%=DropDownList1.ClientID%>").add(option, null);
    <form id="Form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="addItem(); return false;" />
        <asp:DropDownList ID="DropDownList1" runat="server">

No comments: