我正在使用RegularExpressionValidator來驗證文本框。如何分配一個文本標籤在JavaScript中?
現在,如果文本框有效,我需要在標籤控件上顯示「頁面有效」消息。
我會在Code Behind中做它,還是我在javascript本身聲明標籤?
在javascript中我使用了曾嘗試:
document.getElementById("LabelId").innerText="Your Text Here"
,但它顯示微軟JScript運行時錯誤:
Unable to set value of the property 'innerText': object is null or undefined".
而且我一直在使用的innerHTML而不是嘗試過,但它顯示了類似的錯誤。那麼什麼是正確的方式來分配值標籤? 編輯:下面是我的aspx編碼:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="RegularExpressionValidator.aspx.cs" Inherits="ValidationTask.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Label ID="LabelText" runat="server" Text="Label"></asp:Label><br />
<script type="text/javascript" language="javascript">
function ValidatePage() {
debugger;
if (Page_IsValid) {
document.getElementById('<%= LabelText.ClientID %>').innerHTML = 'Page Is Valid';
}
else {
document.getElementById('<%= LabelText.ClientID %>').innerHTML = 'Page is Invalid';
}
}
</script>
<asp:Label ID="LabelZip" runat="server" Text="Enter Zip Code"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Enter" OnClientClick="return ValidatePage()" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TextBox1"
ValidationExpression="\d{5}" runat="server" ErrorMessage="The zip code must be 5 numeric
digits"></asp:RegularExpressionValidator>
</asp:Content>
在此先感謝。
P.S.我是新來的,這是我的第一個問題。如果我犯了錯誤,請忽略。
嘗試在文檔加載或準備好時添加代碼。對象未定義或null在dom中未找到該元素時發生。請參考http://stackoverflow.com/questions/4488714/change-label-text-using-javascript –
嘗試使用標籤的客戶端ID ....像'「<%= LabelId.clientID%>」'或使用檢查元素 –
你可以檢查元素,並確保你有正確的ID? –