DropDownList運用JavaScript實現選項添加與刪除

來源:互聯網
上載者:User

問題情境:

有兩個下拉框ddlPriceType與ddlMonth。代碼分別如下:

 

<asp:DropDownList ID="ddlPriceType" runat="server" onchange="SetMonthByType();">
                    <asp:ListItem Value="0">年度計劃價</asp:ListItem>
                    <asp:ListItem Value="1">月度現行價</asp:ListItem>
                </asp:DropDownList>

 

<asp:DropDownList ID="ddlMonth" runat="server">
                    <asp:ListItem Value="00">全部</asp:ListItem>
                    <asp:ListItem Value="01">一月</asp:ListItem>
                    <asp:ListItem Value="02">二月</asp:ListItem>
                    <asp:ListItem Value="03">三月</asp:ListItem>
                    <asp:ListItem Value="04">四月</asp:ListItem>
                    <asp:ListItem Value="05">五月</asp:ListItem>
                    <asp:ListItem Value="06">六月</asp:ListItem>
                    <asp:ListItem Value="07">七月</asp:ListItem>
                    <asp:ListItem Value="08">八月</asp:ListItem>
                    <asp:ListItem Value="09">九月</asp:ListItem>
                    <asp:ListItem Value="10">十月</asp:ListItem>
                    <asp:ListItem Value="11">十一月</asp:ListItem>
                    <asp:ListItem Value="12">十二月</asp:ListItem>
                </asp:DropDownList>

 

現在想實現的功能是:若ddlPriceType選中第一項,則只能選中ddlMonth下拉框中“全部”,否則可以選中ddlMonth下拉框中除“全部”以外選項。

經過實踐與思考,功能最終得以實現。代碼如下:

 

<script type="text/javascript">
    function SetMonthByType() { 
    
        var control       = $get("<%= ddlPriceType.ClientID %>");
        var selectedValue = control.options[control.selectedIndex].value;
        var month         = $get("<%=ddlMonth.ClientID %>");

        if (selectedValue == "0") 
        {
            if (month.options[0].value != "00") 
            {
                var opt = document.createElement("option"); opt.innerHTML = "全部";opt.value = "00";
                month.insertBefore(opt, month.firstChild);
            }
            month.selectedIndex = 0;
            month.disabled = true;
        }
        else 
        {
            if (month.options[0].value == "00") { month.options.remove(0); }
            month.disabled = false;
        }
    }
</script>

 

註:頁面中DropDownList中初始載入選項時,必須載入全部。然後利用javascript函數對選項進行動態控制。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.