Reputation: 5
I have the used css to set the display of the label to none I am very new to js so I'm not 100% on my code for it..
<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>
Upvotes: 0
Views: 5871
Reputation: 30152
If you are using asp.net 4, then you can set the ClientIdMode of the label to static and reference it like you are. See Rick's post here: http://www.west-wind.com/weblog/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40
You can use a RegularExpressionValidator to validate the length of the textbox.. however based on your comment see the javascript solution below.
http://forums.asp.net/t/1026502.aspx
pure javascript - something like this should work fine.:
<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>
Upvotes: 0
Reputation: 46047
You have arguments in your JS function, but you're not passing any arguments in the onchange event.
Apply the following code to your TextBox:
<asp:TextBox ID="textbox1" CssClass="style5" runat="server" MaxLength="10" onkeyup="strLen(this, 2);"></asp:TextBox>
METHOD #1: Using a Label
Your error label should look like this:
<asp:Label ID="lblError" runat="server" Text="Exceeds max length" style="display:none;"></asp:Label>
And then in your JavaScript function, you can do this:
EDIT: Had logic backwards - changed to: input.value.length > count ? "block" : "none";
strLen = function(input, count){
var errorLabel = document.getElementById("<%=lblError.ClientID%>");
if (errorLabel)
errorLabel.style.display = input.value.length > count ? "block" : "none";
}
METHOD #2: Using a span instead of a Label
Or you could just use a span instead of a label, like this:
<span id="errorLabel" style="display:none;">Exceeds max length</span>
And change the JavaScript function to this:
EDIT: Had logic backwards - changed to: input.value.length > count ? "block" : "none";
strLen = function(input, count){
var errorLabel = document.getElementById("errorLabel");
if (errorLabel)
errorLabel.style.display = input.value.length > count ? "block" : "none";
}
Upvotes: 2