web analytics

charachter validation and count for a textbox – Javascript

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:

<!–[if gte mso 9]> Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <![endif]–><!–[if gte mso 9]> <![endif]–>
<form id="form1″ runat="server">
<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>
<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" ;

Leave a Reply

%d bloggers like this: