I have an ASP.NET control with some text fields and a checkbox. I would like to modify the checkbox state using JavaScript based on the values present in the text fields after page load.
How can I reliably read the text field values in JavaScript? I saw this answer but it didn’t help:
<asp:TextBox Text='<%# Bind("something") %>' ID="txtSomething" runat="server">
</asp:TextBox>
<script type="text/javascript">
alert($('#<%= txtSomething.ClientID %>').val());
</script>
This doesn’t work; VS tells me that “txtSomething is not declared. It may be inaccessible due to its protection level.”
How else can I refer to that text box in JavaScript?
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 try to get client ID of control which contains your text box and after search in his children input which ID contains your text box server ID
<script type="text/javascript">
alert($('#<%= parentControl.ClientID %>').find("input[id$='txtSomething']").val());
</script>
As another option you can do:
<script type="text/javascript">
alert($('#<%= (parentControl.FindControl("txtSomething")).ClientID %>').val());
</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