Good day. I am trying to fetch an asp.net label control’s text value using javascript. However the control id is returned as null when I use
var a = document.getElementById('<%= lblTreatyNo.ClientID %>').innerText;
However it does work when I use the full name from source like
var a = document.getElementById('ctl00_ContentPlaceHolder1_lblTreatyNo').innerText;
I am using master pages in my site design. I want to know the correct way of fetching this. Isn’t there a way not to use the full name from the source file?
Update here is my code sample
<asp:Label ID="lblTreatyNo" runat="server"></asp:Label>
<asp:Button ID="btnNewSec" runat="server" OnClientClick="javascript:void(window.open ('ft_newsec.aspx?ftid='+document.getElementById('ctl00_ContentPlaceHolder1_lblTreatyNo').innerHTML+'',null,'height=220,width=300,resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes')); return false;" Text="Add New Company" CausesValidation="False" Width="155px" />
The only problem that I can see is that you’re trying to get the element before the DOM is loaded. An actual scenario would be if the
asp:Labelis defined after the JavaScript code; by the time the JavaScript code is executed, the element you’re trying to get is not known, anddocument.getElementByIdwill returnnull. But then again, the second approach shouldn’t work neither in this case. We’d need to know more about the context to help you, i.e. the code where both theasp:Labeland the JavaScript code are defined; it looks like something else might be wrong.Regarding your question at the end, using the
ClientIDproperty is the right way to do it, sinceClientIDwill be the value of the element’sidattribute (HTML).Update, in regard to Popo’s newly posted code
lblTreatyNo.ClientIDin theOnClientClickproperty (in the ASPX source) isn’t rendered; if you have a look at the source code of the rendered page, you’ll see something like the following:No server-side code should be put in the
OnClientClickwhen defined in an ASPX page, since the property’s value won’t be rendered. You can imagine thatOnClientClickwill be directly replaced by the JavaScript event handleronclickonce the page is rendered, without renderingOnClientClick‘s value.To circumvent this problem, you either can set the
OnClientClickproperty in the code-behind:Or, if you want to do it on the client-side, you could do the following with jQuery:
Once the DOM is loaded, the above defined jQuery code will attach your JavaScript code to the button’s
clickevent; once the user hits the button, your JavaScript code will be executed.