Posts Tagged ‘textbox character counter’

Here I have provided a solution to put a counter for a textbox, that can be updated as each character typed into the textbox. This script will also validate the maximum character length allowed for a textbox. This script will also work when anyone copy/paste the text into the textbox. Textbox can be either single line or multi line. Check the following script:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100" runat="server" onkeyup="javascript:CharCounter(this.id);" onblur="javascript:CharCounter(this.id);"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function CharCounter(textId)
{
var totalchar = '<%= TextBox1.MaxLength %>';
var txtbox = document.getElementById(textId);
var lbl = document.getElementById('<% =Label1.ClientID %>');
if(txtbox.value.length > totalchar)
{
txtbox.value = txtbox.value.substring(0,totalchar);
}
lbl.innerText = (totalchar - txtbox.value.length) + " chars remaining" ;
}
</script>
</form>
</body>

Happy Coding!!