Get Real-Time Character Counts with Javascript

You may have seen characters counter while sending messages from online free message services or in some cases while filling up online registration forms.In this article you will learn how to create character counter in javascript.

Javascript Code

<script type="text/javascript">
//You can change the counter/limiter value as your wish
var count = "125";  
function limiter() {
	var textvalue = document.demoform.message.value;
	var len = textvalue.length;
	if (len > count) {
		tex = textvalue.substring(0,count);
		document.demoform.message.value =tex;
		return false;
	}
	document.demoform.limit.value = count-len;
}
</script> 

 

HTML Code

<html>
	<body>
	<form name="demoform" method=”post”>
		<table>
		<tr>
			<td><strong>Characters Counter Demo</strong></td></tr>
		<tr>
			<td colspan="2"><textarea name=message rows=3 cols=40 onkeyup=limiter()></textarea></td>
		</tr>
		<tr>
			<td><label style="margin-left:193px;">Characters left :</label></td>
			<td><input type=text name=limit size=4 readonly value="125"></td>
		</tr>
		</table>
	</form>
	</body>
</html>

 

Usage: 

1. Copy the javascript code and Paste it into the head part of your HTML page.
2. You can easily set the limit or counter as your wish.
3. If you wish to restrict the user not to type more than 200 characters in textarea change the count value as 200. This will set the length or size of textarea.

Ketan Patel

As a backend and ecommerce developer, I have extensive experience in implementing robust and scalable solutions for ecommerce websites and applications. I have a deep understanding of server-side technologies and have worked with various programming languages. I have experience in integrating with payment gateways, and other third-party services.