问题
I have the following label control:
<asp:Label ForeColor="DarkGreen" runat="server" ID="lblStatus"></asp:Label>
Its value is filled in the Page_Load event.
I attached the following Javascript (placed at the end of the page, not Master 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 alert(lblObj.value) displays a popup with text "undefined". How can I fix this problem? Please, I tried many combinations for placing the JavaScript but no luck! Thanks
UPDATE
Browser soruce code:
<span id="ctl00__main_lblStatus" style="color:DarkGreen;">Available</span></td>
First line of Validate JS function:
function Validate() {
var lblObj = document.getElementById('ctl00__main_lblStatus');
回答1:
Use JQuery and it will run in all browsers and platforms, something like:
$('#<%= lblStatus.ClientID %>').next().text();
source: JQuery: getting the value/text/innerHtml of a checkbox in an ASP.NET CheckBoxList control
回答2:
labels don't have a value. They have innerHTML and innerText.
回答3:
Label server control renders as span. So you should get it's content by innerText. try this :
alert(lblObj.innerText);
回答4:
ASP.NET label server control will be rendered in complex HTML output. Like:
<span id="ctl00_ctl00_ContentPlaceHolder1_BodyPlaceHolder_lblLanguage0">
<label class="inputText">English</label>
</span>
When you use getElementById you will get span. But to set value via javascript you have to access inner label object
回答5:
try this
<script language="javascript" type="text/javascript">
function getlabelvalue()
{
var value1 = document.getElementById('<%=labelID.ClientID%>').value;
if (value1.length < 1)
value1 = 0;
}
</script>
回答6:
With jquery you need to use the html method.
var g = $('#<%=lblStatus.ClientID%>').html();
These will NOT work with jquery:
- $('#<%=lblStatus.ClientID%>').innerText
- $('#<%=lblStatus.ClientID%>').innerHTML
- $('#<%=lblStatus.ClientID%>').val()
来源:https://stackoverflow.com/questions/7431464/how-to-use-javascript-to-get-asp-net-web-forms-labels-value