How to use Javascript to get ASP.NEt Web Forms tag label value?

I have the following label control:

<asp:Label ForeColor="DarkGreen" runat="server" ID="lblStatus"></asp:Label> 

Its value is populated with the Page_Load event.

I attached the following Javascript (placed at the end of the page , not the main page):

 function Validate() { var lblObj = document.getElementById('<%=lblStatus.ClientID%>'); alert(lblObj.value); if (lblObj.value == "Replaced" || lblObj.value == 'Trashed' || lblObj.value == "Internal Use") { alert("Products with" + lblObj.value + "status cannot be reserved"); return false; } } 

The message (lblObj.value) displays a pop-up window with the text "undefined". How can I fix this problem? Please, I tried many combinations to host JavaScript, but no luck! Thanks

UPDATE

Browser code:

 <span id="ctl00__main_lblStatus" style="color:DarkGreen;">Available</span></td> 

The first line of the Validate JS function:

 function Validate() { var lblObj = document.getElementById('ctl00__main_lblStatus'); 
+4
source share
6 answers

Use jQuery and it will run in all browsers and platforms, for example:

 $('#<%= lblStatus.ClientID %>').next().text(); 

source: JQuery: getting the value / text / innerHtml of a flag in an ASP.NET CheckBoxList control

+4
source

label do not have value . They have innerHTML and innerText .

+5
source

Label server management is performed as a range. So you should get its contents through innerText. try the following:

 alert(lblObj.innerText); 
+4
source

ASP.NET-based label server management will appear in a complex release of HTML. How:

 <span id="ctl00_ctl00_ContentPlaceHolder1_BodyPlaceHolder_lblLanguage0"> <label class="inputText">English</label> </span> 

When you use getElementById you will get a range. But to set the value via javascript you need to access the internal label object

+2
source

try it

 <script language="javascript" type="text/javascript"> function getlabelvalue() { var value1 = document.getElementById('<%=labelID.ClientID%>').value; if (value1.length < 1) value1 = 0; } </script> 
+1
source

Using jquery you need to use the html method.

 var g = $('#<%=lblStatus.ClientID%>').html(); 

They will not work with jquery:

  • $ ('# <% = lblStatus.ClientID%>'). innerText
  • $ ('# <% = lblStatus.ClientID%>'). InnerHTML
  • $ ('# <% = lblStatus.ClientID%>'). Shaft()
+1
source

All Articles