【问题标题】:Getting the value of a dropdown list by javascript is not working.通过 javascript 获取下拉列表的值不起作用。
【发布时间】:2011-08-04 14:48:18
【问题描述】:

我已经做了一百万次,每次都成功了,但这次我无法让它工作,我不知道为什么。

我有一个下拉列表,我需要在 javascript 中获取下拉列表的选定值。

    <asp:DropDownList runat="server" ID="ddlCompanies"  AutoPostBack="true">
    <asp:ListItem Value="Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-7329,USA">Microsoft Corporation</asp:ListItem> 
    <asp:ListItem Value="1600 Amphitheatre Parkway, Mountain View, CA 94043">Google Inc.</asp:ListItem> 
    <asp:ListItem Value="500 Oracle Parkway,Redwood Shores, CA 94065">Oracle Corporation</asp:ListItem> 
    <asp:ListItem Value="One Dell Way,Round Rock, Texas 78682,United States">Dell Inc.</asp:ListItem> 
    </asp:DropDownList>

我的 javascript 代码是:

    function findAddress() {
    if (document.getElementById("ddlCompanies") == null )
    return false;
    else{
     var ddlAddress = document.getElementById("ddlCompanies");
     var value = ddlAddress.getAttribute('value');
     var dllAddressIndex = ddlAddress.selectedIndex;
     var dllAddressValue = dllAddressIndex.value;
     var options = dllAddress.options[0];
            var address = ddlAddress.options[ddlAddress.selectedIndex].value;  // get selected address from dropdownlist
            showAddress(address); 
            return false;   // avoid postback
            }
    }

我在firebug中以调试模式运行这段代码,我可以清楚地看到所选索引的值为null。事实上,代码在到达 dllAddress.options 时会中断。我也试过.text而不是.value,它仍然不起作用。请帮助我在这上面花了 2 天时间。谢谢。

他们不让我发布萤火虫调试器的图像,但我可以看到 selectedindex 被 javascript 拾取,但值仍然为空。

【问题讨论】:

    标签: javascript asp.net list drop-down-menu


    【解决方案1】:

    由于没有名为 'dllAddress' 的变量,它的值为 null。尝试将其更改为您在 else 块顶部定义的“ddlAddress”。

    将来,您可能还会考虑不使用靠得太近的变量名... :)

    【讨论】:

    • 谢谢。我真的很尴尬!
    【解决方案2】:
    var options = dllAddress.getElementsByTagName("option")[0];
    

    【讨论】:

    • 我没有一个名为 options 的元素,出于调试目的,我放了那行,看看我能不能得到任何东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2018-11-09
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多