Limit Character Count in HTML Textarea
EasyProgramming.net tutorial on how to count and limit characters in an HTML textarea
by Nazmus Nasir
HTML
<!-- Easy JavaScript # 33 - Character Count Limit -->
<p>
Welcome to the 33rd Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. Let's create a script that keeps track of the number of characters we input in a textarea!
</p>
<p>
What you'll need to know: Array Methods, Event Listeners, String Methods, input/output (and other basics)
</p>
<p>
Let's take a look!
</p>
<p>
<textarea id="myText" height="500"></textarea>
</p>
<p>
<span id="wordCount">0</span> Characters
</p>
CSS
textarea {
width: 500px;
height: 150px;
}
JavaScript
var myText = document.getElementById("myText");
var wordCount = document.getElementById("wordCount");
myText.addEventListener("keyup",function(){
var characters = myText.value.split('');
wordCount.innerText = characters.length;
if(characters.length > 150){
myText.value = myText.value.substring(0,150);
wordCount.innerText = 150;
}
});