Count characters in textarea
What errors are you seeing in the browser? I can understand why your code doesn't work if what you posted was incomplete, but without knowing that I can't know for sure.
You should probably clear the charNum div, or write something, if they are over the limit.
function countChar(val) {
var len = val.value.length;
if (len >= 500) {
val.value = val.value.substring(0, 500);
} else {
$('#charNum').text(500 - len);
}
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea id="field" onkeyup="countChar(this)"></textarea>
<div id="charNum"></div>
⚠️ The accepted solution is flawed.
Here are two scenarios where the keyup
event will not get fired:
- The user drags text into the textarea.
- The user copy-paste text in the textarea with a right click (contextual menu).
Use the HTML5 input
event instead for a more robust solution:
JavaScript (demo):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", ({ currentTarget: target }) => {
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
<textarea maxlength='140'></textarea>
And if you absolutely want to use jQuery:
$('textarea').on("input", function() {
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if (currentLength >= maxlength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(maxlength - currentLength + " chars left");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<textarea maxlength='140'></textarea>