我正在尝试对我的注册页面进行服务器+客户端验证。我想在我的TextBox控件失去焦点(onBlur)时调用JS函数。
aspx页面中的代码
<div id="nameDiv">
<asp:UpdatePanel ID="updatePanelName" runat="server">
<ContentTemplate>
<asp:Label ID="labelName" runat="server" Text="Enter Your Name"></asp:Label>
<asp:TextBox ID="textBoxName" runat="server" placeholder="Enter Your Name"
onBlur="check(this)"></asp:TextBox>
<i class="fa fa-exclamation-circle errorSign" id="errorIcon" runat="server"></i>
<asp:Label ID="labelNameError" runat="server" Text="Name can't be blank" ForeColor="Red">
</asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
JavaScript代码
function check(txtBox) {
var errIcon = document.getElementById("<%= errorIcon.ClientID %>");
txt = txtBox.value;
if (txt.length < 1)
errIcon.style.visibility = "visible";
}
CSS
input[type=text] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display:inline-block;
position:relative;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.errorSign{
position:absolute;
margin-right:30px;
left:1050px;
top:220px;
visibility:hidden;
}
答案 0 :(得分:1)
OP在评论中表示...
是其外部js文件
失败的原因是ASP.Net不处理.js
文件,这些文件将被发送到浏览器而没有任何更改。这意味着浏览器正在接收与编写时完全相同的行...
var errIcon = document.getElementById("<%= errorIcon.ClientID %>");
有多种方法可以解决此问题……第一种可能不理想,但是它是将脚本放入您的.aspx
或.ascx
文件中。
这意味着脚本(属于ASP.Net处理页面的一部分)将具有控件的实际id
,而不是<%=..%>
。
第二种可能更好的方法是直接使用class
名称,而不是id
...
var errIcon = document.getElementsByClassName("errorSign")[0];
由于getElementsByClassName
返回一个元素数组(因为页面上的多个元素可能具有相同的类),因此上述方法将返回该数组中的第一项。如果您的代码更复杂,则需要进行相应的修改
另一种选择(感谢@epascarello)是使用nextElementSibling
,但是如果您出于某种原因更改HTML(例如重新设计页面),则很可能会中断... >
var errIcon = txtBox.nextElementSibling;