javascript 错误:无法读取 null 的属性“选项”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31695876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:11:44  来源:igfitidea点击:

javascript error: Cannot read property 'options' of null

javascriptjqueryasp.net

提问by user123456789

I have a GridView that has a column with a textbox where the user can enter a value and a column with a dropdownlist. If the user enter a values that is not equal to 1 in the textbox, they must select a value from the dropdownlist. The default value in the DDL is "Select" which is just an empty value that was coded in: ddlReasons.Items.Insert(0, new ListItem("Select"));. The DDL is created dynamically but select will always be the default value.

我有一个 GridView,它有一列带有一个文本框,用户可以在其中输入一个值和一个带有下拉列表的列。如果用户在文本框中输入一个不等于 1 的值,他们必须从下拉列表中选择一个值。DDL 中的默认值是“Select”,它只是一个编码为的空值:ddlReasons.Items.Insert(0, new ListItem("Select"));。DDL 是动态创建的,但 select 将始终是默认值。

 function UpdateSerialQtyRcvd(SerNoID, QtyRcvd) {
        if (QtyRcvd != 1) {
            var ddl = document.getElementById("ddlReasons");
            var selectedValue = ddl.options[ddl.selectedIndex].value;
            if (selectedValue == "Select") {
                alert("Must select reason");
            }

        }
        else {
            PageMethods.UpdateSerialQtyRcvdUserControl(SerNoID, QtyRcvd, OnUpdateSuccess, OnUpdateFail);
        }
    }

If the user enters a value that is not 1 then I need to check what value is in the DDL. If "Select" is the value I need the user to select something else in the DDL but I am getting this error on the line var selectedValue = ddl.options[ddl.selectedIndex].value;

如果用户输入的值不是 1,那么我需要检查 DDL 中的值。如果“选择”是我需要用户在 DDL 中选择其他内容的值,但我在线上收到此错误var selectedValue = ddl.options[ddl.selectedIndex].value;

Uncaught TypeError: Cannot read property 'options' of null

未捕获的类型错误:无法读取 null 的属性“选项”

Code for dropdownlist:

下拉列表的代码:

<asp:TemplateField HeaderText="Reason">
 <ItemTemplate>
  <asp:DropDownList ID="ddlReasons" runat="server" class="ReasonDDL" ></asp:DropDownList>
 </ItemTemplate> 
</asp:TemplateField>

采纳答案by christiandev

You'll need to get the ClientId...

您需要获取ClientId...

Javascript:

Javascript:

var ddl = document.getElementById("<%=ddlReasons.ClientID%>");

JQuery:

查询

var ddl = $('#<%=ddlReasons.ClientID%>');

Check out the MSDN documentationon how to access the Client ID and the different settings.

查看MSDN documentation有关如何访问客户端 ID 和不同设置的信息。

回答by Parthipan Natkunam

One more way to do it using JQuery:

使用JQuery 的另一种方法:

var ddlReason = $("[id*=ddlReasons]");
var selectedValue = ddlReason.val();