在JavaScript中正确引用ASP.NET用户控件中的控件

时间:2022-10-19 21:40:40

I have an ASP.NET user control that contains a text box control and a button control. This user control will be added to my web-page many times. I need to have a piece of JavaScript that will run whenever the text box changes, and disable the button if the value of the text box is invalid. My question is this: how do I put JavaScript on the textbox that can reference only the button that is in the same user control? Remember, there are many ASP.NET user controls, each with a button and a text box, and I only want the invalid value in a text box to affect the one associated button. Thanks!

我有一个ASP.NET用户控件,其中包含一个文本框控件和一个按钮控件。此用户控件将多次添加到我的网页中。我需要有一段JavaScript,只要文本框改变就会运行,如果文本框的值无效,则禁用该按钮。我的问题是:如何将JavaScript放在只能引用同一用户控件中的按钮的文本框中?请记住,有许多ASP.NET用户控件,每个控件都有一个按钮和一个文本框,我只希望文本框中的无效值影响一个关联的按钮。谢谢!

1 个解决方案

#1


You can use ClientId property of controls (it's uniquely identifies control on the client side) and make something like that:

您可以使用控件的ClientId属性(它在客户端唯一标识控件)并进行类似的操作:

<asp:TextBox runat="server" ID="myTextBox" />
<asp:Button runat="server" ID="myButton" Text="click" />

<script language="javascript" type="text/javascript">
    document.getElementById("<%=myTextBox.ClientID %>").onclick = function() {
        document.getElementById("<%=myButton.ClientID %>").disabled = "disabled";
    }
</script>

Also refer to this document: Client Script in ASP.NET Web Pages, section Referencing Server Controls in Client Script

另请参阅此文档:ASP.NET网页中的客户端脚本,在客户端脚本中引用服务器控件一节

#1


You can use ClientId property of controls (it's uniquely identifies control on the client side) and make something like that:

您可以使用控件的ClientId属性(它在客户端唯一标识控件)并进行类似的操作:

<asp:TextBox runat="server" ID="myTextBox" />
<asp:Button runat="server" ID="myButton" Text="click" />

<script language="javascript" type="text/javascript">
    document.getElementById("<%=myTextBox.ClientID %>").onclick = function() {
        document.getElementById("<%=myButton.ClientID %>").disabled = "disabled";
    }
</script>

Also refer to this document: Client Script in ASP.NET Web Pages, section Referencing Server Controls in Client Script

另请参阅此文档:ASP.NET网页中的客户端脚本,在客户端脚本中引用服务器控件一节