Reputation: 53
I tried all the possible solutions to get the value of an element by id, but it did not work. I am using ASP.NET, I have searched for the controls and I know that the server changes the id of the TextBox1
, so we use the clientID
. But when I write console.log(data1), I get nothing 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 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 master file!
console.log(data1);
appears in the console as empty place.
If anyone knows another way or why it is not working, please tell me.
Upvotes: 5
Views: 23208
Reputation: 270
1.You may be having the same problem as in this question:
Javascript Get Element by Id and set the value
If the page hasn't loaded that element yet before your javascript runs getElementById will return null.
"So, make sure your [element] does exist in the page, and then call [getElementById], you can use window.onload or $(document).ready function."
2.The error:
Uncaught SyntaxError: Unexpected end of input and its reference in the master file
may be caused by a missing braket or other formatting error. Double check everything is written correctly.
Upvotes: 0
Reputation: 14624
Id of server controls gets changed and is appended with content place holder id so a very easy solution is to set a property ClientIDMode="static"
on server controls. By setting this id of control will remain same and will not get changed so you will find it by getElementById
in javascript.
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="static" ></asp:TextBox>
Upvotes: 8
Reputation: 23
you can try like this to get master page control value in content page. document.getElementById('<%=Master.FindControl("Textbox1").ClientID %>'). If it's same page then you should be able to use directly document.getElementById("<%=TextBox1.ClientID %>").
Upvotes: 2