Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element by id in ASP.NET?

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.

like image 345
Raghda Mohamed Avatar asked Jun 03 '15 14:06

Raghda Mohamed


2 Answers

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>
like image 191
Mairaj Ahmad Avatar answered Nov 10 '22 09:11

Mairaj Ahmad


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 %>").

like image 1
Barani Avatar answered Nov 10 '22 09:11

Barani