문제

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

도움이 되었습니까?

해결책

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);

다른 팁

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.

Include jQuery in your page and use this script:

<script>
$(document).ready(function(){
    alert($("#lbl").text());
});
</script>

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

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

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

$find('<%=((Label)Master.FindControl("lbl")).ClientID %>');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top