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.
<!DOCTYPE html><html> <head> <script src="http://code.jquery.com/jquery-1.5.js"></script> <script> function countChar(val) { var len = val.value.length; if (len >= 500) { val.value = val.value.substring(0, 500); } else { $('#charNum').text(500 - len); } }; </script> </head> <body> <textarea id="field" onkeyup="countChar(this)"></textarea> <div id="charNum"></div> </body></html>
... works fine for me.
Edit: You should probably clear the charNum div, or write something, if they are over the limit.
⚠️ 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:
<textarea maxlength='140'></textarea>
JavaScript (demo):
const textarea = document.querySelector("textarea");textarea.addEventListener("input", event => { const target = event.currentTarget; 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`);});
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 ){ console.log("You have reached the maximum number of characters."); }else{ console.log(maxlength - currentLength + " chars left"); }});
Improved version based on Caterham's function:
$('#field').keyup(function () { var max = 500; var len = $(this).val().length; if (len >= max) { $('#charNum').text(' you have reached the limit'); } else { var char = max - len; $('#charNum').text(char + ' characters left'); }});