Character Count Limiter
Give feedback as they type. This script monitors keystrokes in a textarea and updates a counter to show how many characters are allowed.
100 characters remaining
Copy the Script
<script>
function countChars(obj) {
var maxLength = 100;
var strLength = obj.value.length;
var charRemain = (maxLength - strLength);
if(charRemain < 0){
document.getElementById("charNum").innerHTML = 'Limit exceeded';
}else{
document.getElementById("charNum").innerHTML = charRemain + ' remaining';
}
}
</script>
<textarea onkeyup="countChars(this)" maxlength="100"></textarea>
<p id="charNum">100 remaining</p>
Frequently Asked Questions
Yes, the HTML `maxlength` attribute stops users from typing more. This script adds the *visual feedback* (e.g., '10 characters left') which `maxlength` does not provide.
Yes. You would split the value by spaces (`value.split(' ').length`) instead of checking `value.length`.
Yes. Add logic: `if (remaining < 10) span.style.color = 'red';` to warn the user visually.