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.

+3


source to share


4 answers


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>

      

+2


source


set property ClientIDMode="static"

on server controls.

then use getElementById

in javascript.



<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="static" ></asp:TextBox>

      

+1


source


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.

0


source


you can try doing this to get the master page value in the content page. document.getElementById ('<% = Master.FindControl ("Textbox1"). ClientID%>'). If on the same page, you should be able to directly use document.getElementById ("<% = TextBox1.ClientID%>").

0


source







All Articles