简体   繁体   English

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

[英]Getting the value of a dropdown list by javascript is not working.

I have done this a million time and every time has worked, but I cannot get it to work this time and I have no clue why. 我已经完成了100万次,并且每次都有效,但是这次我无法使其正常工作,我也不知道为什么。

I have a dropdown list and I need to get the selected value of the dropdown list in javascript. 我有一个下拉列表,我需要在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>

My javascript code is: 我的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
            }
    }

I run this code in debug mode in firebug and I can clearly see that the value of the selected index is null. 我在firebug中以调试模式运行此代码,并且可以清楚地看到所选索引的值为null。 In fact, the code breaks when it reaches dllAddress.options. 实际上,代码到达dllAddress.options时就会中断。 I also tried .text instead of .value, it still doesn't work. 我还尝试了.text而不是.value,它仍然无法正常工作。 Please help I have spent 2 days on this. 请帮助我在此上花了2天。 Thanks. 谢谢。

They don't let me to post an image of firebug debugger, but I can see that the selectedindex is picked up by javascript, but the value remains null. 他们不允许我发布Firebug调试器的图像,但我可以看到javascript拾取了selectedindex,但该值仍然为null。

Since there is no variable named 'dllAddress', it will have a value of null. 由于没有名为“ dllAddress”的变量,因此它将具有null值。 Try changing it to 'ddlAddress' which you defined at the top of the else block. 尝试将其更改为您在else块顶部定义的“ ddlAddress”。

In the future, you might also consider not using variable names that are so close together... :) 将来,您可能还会考虑不要使用过于紧密的变量名... :)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM