2012-08-10

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>
<html>
<head>
    <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);
            }
        }
    </script>
</head>
<body>
    <form id="Form1" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="addItem(); return false;" />
    <p>
        Options-
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </p>
    </form>
</body>
</html>

No comments: