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.
I have a dropdown list and I need to get the selected value of the dropdown list in javascript.
<asp:DropDownList runat="server" ID="ddlCompanies" AutoPostBack="true"&开发者_运维技巧gt;
<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:
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. In fact, the code breaks when it reaches dllAddress.options. I also tried .text instead of .value, it still doesn't work. Please help I have spent 2 days on this. 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.
Since there is no variable named 'dllAddress', it will have a value of null. Try changing it to 'ddlAddress' which you defined at the top of the else block.
In the future, you might also consider not using variable names that are so close together... :)
var options = dllAddress.getElementsByTagName("option")[0];
精彩评论