通过javascript获取下拉列表的值不起作用。

时间:2011-08-04 14:48:18

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

我已经完成了一百万次,每次都有效,但这次我不能让它工作,我不知道为什么。

我有一个下拉列表,我需要在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天时间。感谢。

他们不允许我发布firebug调试器的图像,但是我可以看到所选的索引是由javascript拾取的,但是值仍为null。

2 个答案:

答案 0 :(得分:1)

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

将来,您可能还会考虑不使用如此接近的变量名......:)

答案 1 :(得分:0)

var options = dllAddress.getElementsByTagName("option")[0];