2

I am trying to access control in Master page from Content page(Asp.net) using javascript like this

alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').value);

control in Master page is as follow,

 <asp:Label ID="lbl" runat="server" Text="one"></asp:Label>

But unfortunately it is not working. I am getting undefined value

user3411907
  • 21
  • 1
  • 1
  • 4
  • In what way is it not working? Do you get an `Exception` from .NET or an `undefined` value in the alert? The [`FindControl()`](http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx) method is not recursive, so unless your `lbl` control is a direct children of `Master`, it won't be found. – juan.facorro Mar 12 '14 at 17:26
  • so what is the solution? how can I correct it? – user3411907 Mar 12 '14 at 17:29
  • I get undefined value – user3411907 Mar 12 '14 at 17:33
  • Why you don't use a pure javascript solution? jQuery helps you a lot: `$("#parent").find(".contrl-class-name").val(); `. If you give us more information, we'd give you better answer. – Maysam Mar 12 '14 at 17:34
  • I know it works, I have worked on project where it's working fine. I am just missing something that's why I asking for help – user3411907 Mar 12 '14 at 17:38

5 Answers5

2

I noticed that you are actually accessing the .value field of the element that the <asp:Label /> control generates, which is a <span></span>. This type of element won't return anything for the .value attribute. If you are actually trying to access its text then use:

alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').innerText);

or

alert(document.getElementById('<%=((Label)Master.FindControl("lbl")).ClientID %>').innerHTML);
juan.facorro
  • 9,791
  • 2
  • 33
  • 41
1

The problem is that a master page is a naming container, hence the client id of the control receives a prefix which is the id of the naming container. Using JavaScript, it is easily solvable:

var elm = document.querySelector('[id$="lbl"]');

$= means, ends with.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74
0

Include jQuery in your page and use this script:

<script>
$(document).ready(function(){
    alert($("#lbl").text());
});
</script>
Maysam
  • 7,246
  • 13
  • 68
  • 106
0

This is work for me:(Check the below code)

alert(document.getElementById('<%=(Master.FindControl("lbl")).ClientID %>').innerText);
Veera
  • 3,412
  • 2
  • 14
  • 27
0

Using getElementById didn't work for me. The following can be used instead:

$find('<%=((Label)Master.FindControl("lbl")).ClientID %>');
Pieriv
  • 1
  • 1