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!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use ClientId property of controls (it’s uniquely identifies control on the client side) and make something like that:
<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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0