Reputation: 81
I have set my textbox maxlength to 20, where I am using validation control to give the error message and it works fine, but actually I want it to display character count the moment user starts entering input in textbox and when it reaches 20 character then user should not be able to type in it. Can this be done, Can anyone shed light on it please:
Upvotes: 0
Views: 3034
Reputation: 21
VB.NET
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
If TextBox1.Text.Length >= 25 Then
If e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End If
End Sub
'25 is the Limit User Input
Upvotes: 0
Reputation: 5002
I write this code as simple as possible. You need handle some other event such as onPaste as well and write it more efficient. By the way.
I assumed: You have jQuery:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
And these Control:
<asp:TextBox ID="txtMessage" TextMode="MultiLine" runat="server"></asp:TextBox>
<asp:Label ID="lblCount" runat="server"></asp:Label>
You need just some JavaScript code like this:
<script>
var max = 20;
var lblCount = $("[id$='lblCount']");
var txtMessage = $("[id$='txtMessage']");
function checkCount(padding) {
var currentLength = txtMessage.val().length;
if (currentLength >= 20) {
return false;
} else {
lblCount.text(max - currentLength - padding);
}
return true;
}
lblCount.text(max);
txtMessage.keypress(function (e) {
var key = e.keyCode || e.which;
if (key != 8 && key != 46) {
if (!checkCount(1)) {
e.preventDefault();
};
};
});
txtMessage.keyup(function (e) {
var key = e.keyCode || e.which;
if (key != 8 && key != 46) {
e.preventDefault();
return;
}
checkCount(0);
});
</script>
In very start part of JavaScript code I defined max, lblCount an txtMessage that you must be aware of them.
Upvotes: 0
Reputation: 8271
You need to use Javascript for this :
JS
function tocheck(field, count, limit)
{
if (field.value.length > limit)
field.value = field.value.substring(0, limit);
else
count.value = limit - field.value.length;
}
Asp.net
<asp:TextBox ID="txtMessage" TextMode="MultiLine" Width="200px" Rows="3"
runat="server" onkeyup="tocheck(txtMessage, this.form.remLen, 20);" onkeydown="tocheck(txtMessage, this.form.remLen, 20);" />
In another textbox you check the count:
<input readonly="readonly" type="text" name="remLen" size="3" maxlength="3" value="160" />
Upvotes: 1