How to get an element by id in ASP.NET?
I tried every possible solution to get the value of an element by id, but it didn't work. I am using ASP.NET, I was looking for controls and I know the server is changing the ID TextBox1
, so we are using clientID
. But when I write console.log (data1) I am not getting anything or empty space.
var data1 = document.getElementById('MainContent_TextBox1').textContent;
var data1 = document.getElementById("<%=MainContent_TextBox1.ClientID %>").value;
This is the ASPX code:
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
And this is the JS code:
var data1 = document.getElementById('MainContent_TextBox1').textContent;
In the console I get this error:
Uncaught SyntaxError: Unexpected end of input and its reference in the main file!
console.log(data1);
appears in the console as empty space.
If anyone knows another way or why it doesn't work, please tell me.
source to share
The ID of the server controls is modified and appended with the ID of the content owner, so a very simple solution is to set the property ClientIDMode="static"
on the server controls. By setting this control ID, it will remain the same and will not be changed, so you will find it getElementById
in javascript.
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="static" ></asp:TextBox>
source to share
1. You may have the same problem as in this question:
Javascript Get element by id and set value
If the page hasn't loaded this element even before javascript has run, getElementById will return null.
"So, make sure your [element] exists on the page, and then [getElementById] is called, you can use window.onload or $ (document) .ready."
2. Error: Uncaught SyntaxError: Unexpected end of input and its reference in the master file
May be caused by a missing border or other formatting error. Double check: everything is written correctly.
source to share