如何使用带有asp文本框的onchange事件的javascript更改asp标签的可见性

时间:2011-08-19 16:07:30

标签: javascript asp.net event-handling

我有用过的css将标签的显示设置为none 我是js的新手,所以我不是100%在我的代码上...

<script type="text/javascript">
function strLen(field, count)
{
var str = document.getElementById("textbox1");
if(str.value.length > 2)
{
document.getElementById("errorLabel").style.display = 'inherit';
}
}
</script>
<asp:textbox id="textbox1" CssClass="style5" runat="server" MaxLength="10"         onchange="strLen()"></asp:textbox>

2 个答案:

答案 0 :(得分:2)

你的JS函数中有参数,但你没有在onchange事件中传递任何参数。

将以下代码应用于TextBox:

<asp:TextBox ID="textbox1" CssClass="style5" runat="server" MaxLength="10" onkeyup="strLen(this, 2);"></asp:TextBox>

方法#1 :使用标签

您的错误标签应如下所示:

<asp:Label ID="lblError" runat="server" Text="Exceeds max length" style="display:none;"></asp:Label>

然后在你的JavaScript函数中,你可以这样做:

编辑:向后逻辑 - 更改为:input.value.length&gt;数? “阻止”:“无”;

strLen = function(input, count){
    var errorLabel = document.getElementById("<%=lblError.ClientID%>");
    if (errorLabel)
        errorLabel.style.display = input.value.length > count ? "block" : "none";
}

方法#2 :使用跨度而不是标签

或者您可以使用跨度而不是标签,如下所示:

<span id="errorLabel" style="display:none;">Exceeds max length</span>

将JavaScript函数更改为:

编辑:向后逻辑 - 更改为:input.value.length&gt;数? “阻止”:“无”;

strLen = function(input, count){
    var errorLabel = document.getElementById("errorLabel");
    if (errorLabel)
        errorLabel.style.display = input.value.length > count ? "block" : "none";
}

答案 1 :(得分:0)

如果您使用的是asp.net 4,那么您可以将标签的ClientIdMode设置为static并像您一样引用它。请看Rick的帖子: http://www.west-wind.com/weblog/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40

您可以使用RegularExpressionValidator来验证文本框的长度..但是根据您的评论,请参阅下面的JavaScript解决方案。

http://forums.asp.net/t/1026502.aspx

纯粹的javascript - 这样的事应该可以正常工作。:


 <div id="lengthInfo" style="display:none">Too long!!</div>
 <script type="text/javascript">
     function strLen(textBox) {
         var str = textBox.value;
         if (str.length > 2) {
             document.getElementById("lengthInfo").style.display = 'inline';
         }
         else {
             document.getElementById("lengthInfo").style.display = 'none';
         }
     }
</script>
<asp:textbox id="textbox1" CssClass="style5" ClientIDMode="Static" runat="server" MaxLength="10" onkeyup="strLen(this)"></asp:textbox>