Posts Tagged ‘javascript textbox character counter’

Few months back I have posted one article on “Javascript: Maximum character validation and character counter for a textbox”, now here I have given one example on how to count words out of any textarea or textbox.

The counter of word will get incremented as you type in each word (one spell) into the textbox/textarea. This script will also work when anyone copy/paste the text into the textbox (copy/paste should not through mouse). Check the following script:

<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100"
runat="server" onkeyup="javascript:WordCounter(this.id,'Label1');"
onblur="javascript:WordCounter(this.id,'Label1');"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars
remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function WordCounter(textId,lblID)
{
var this_field = document.getElementById(textId);
var label = document.getElementById(lblID);
var char_count = this_field.value.length;
var fullStr = this_field.value + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;
if (fullStr.length <2)
{
word_count = 0;
}
if (word_count == 1)
{
wordOrWords = " word";
}
else
{
wordOrWords = " words";
}
if (char_count == 1)
{
charOrChars = " character";
}
else
{
charOrChars = " characters";
}
label.innerHTML = word_count + wordOrWords;
}
</script>
</form>
</body>

Happy Coding!!

Advertisements

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!!