Count textarea characters
Solution 1
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQuery
using the following code. (Thanks @Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
Solution 2
⚠️ The accepted solution is outdated.
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");
}
});
Solution 3
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are calling textareaLengthCheck
and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
var length = textarea.length;
textarea
is the actual textarea, not the value. Try this instead:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
Solution 4
Here is simple code. Hope it help you
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
Solution 5
This code gets the maximum value from the maxlength
attribute of the textarea
and decreases the value as the user types.
<DEMO>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
Ilan Biala
I'm a senior electrical and computer engineering major at Carnegie Mellon University with experience, in systems programming, full-stack development, API design and implementation, and DevOps.
Updated on July 08, 2021Comments
-
Ilan Biala almost 3 years
I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
$(document).ready(function() { var tel1 = document.forms["form"].elements.tel1; var tel2 = document.forms["form"].elements.tel2; var textarea = document.forms["form"].elements.textarea; var clock = document.getElementById("clock"); var count = document.getElementById("count"); tel1.addEventListener("keyup", function (e){ checkTel(tel1.value, tel2); }); tel2.addEventListener("keyup", function (e){ checkTel(tel2.value, tel3); }); /*$("#textarea").keyup(function(){ var length = textarea.length; console.log(length); var charactersLeft = 500 - length; console.log(charactersLeft); count.innerHTML = "Characters left: " + charactersLeft; console.log("Characters left: " + charactersLeft); });​*/ textarea.addEventListener("keypress", textareaLengthCheck(textarea), false); }); function checkTel(input, nextField) { if (input.length == 3) { nextField.focus(); } else if (input.length > 0) { clock.style.display = "block"; } } function textareaLengthCheck(textarea) { var length = textarea.length; var charactersLeft = 500 - length; count.innerHTML = "Characters left: " + charactersLeft; }
-
Ilan Biala over 11 yearsI want it to say "Characters left: xxx" xxx being a number 500 or lower.
-
Ilan Biala over 11 yearstextarea is the variable I made earlier in the javascript file if you look at the top of my jquery ready function.
-
Andrew Hubbs over 11 yearsUpdated to say what you wanted.
-
Ilan Biala over 11 yearsexactly that and for some reason it said NaN after I typed something, lemme try your snippet.
-
Ilan Biala over 11 yearsCool, yours works, I think I missed the last quotes for the string part of the text. Thanks.
-
Niet the Dark Absol over 11 yearsYes, and it contains the textarea itself, not its value.
-
Niet the Dark Absol over 11 yearsReplace code with
document.getElementById('textarea').onkeyup = function() {document.getElementById('count').innerHTML = "Characters left: "+(500-this.value.length);};
and it will run about a hundred times faster ;) -
Ilan Biala over 10 years@NiettheDarkAbsol Why would that be faster?
-
Ilan Biala over 10 yearsfor this operation, I think it's only 1-2 ms we're talking about here...so I'm not too concerned.
-
Wracker over 9 yearsit does not update the counter while holding down any key. So I quess it would also worth adding another handler for $("#textarea")keydown( .. )
-
Cassandra over 9 years@NiettheDarkAbsol Please format your code correctly for SO, so that others who may be interested can clearly follow.
-
Cassandra over 9 years@NiettheDarkAbsol well it doesn't work as presented, for starters. Code should have four spaces before each line so it formats clearly. Read the notes below the comment box next time you're entering a comment. It's right there. And to me, it looks like your code is partial and not full. As it is it does not function.
-
Niet the Dark Absol over 9 years@Cassandra You cannot do code blocks in comments. My code works fine
-
Cassandra over 9 years@NiettheDarkAbsol Point taken re not being able to do code blocks in comments. Perhaps it would have been better suited as an answer anyway. :) Your code breaks on the page I've tried to use it on, however I've another answer from here that I am modifying and implementing now. Would have liked to have used yours, but wasn't presented well at the time.
-
Lara about 6 yearsSimple and elegant. Thank you. jQuery is fine but I really wish there were more pure javascript solutions like yours.
-
Edouard Reinach almost 5 yearsThis is a better solution
-
LUISAO over 3 yearsI liked this solution. Thank you!
-
Camaleo about 3 yearson the element change
<textarea onKeyUp="
to<textarea onKeyDown="
as sometimes the first char is not counted – in my case I have several textareas in the same page and used your code in a function:function limitInput( id, i ) { var el_t = document.getElementById( id ); var length = el_t.getAttribute( "maxlength" ); var el_c = document.getElementById( 'count-' + i ); el_c.innerHTML = length; el_t.onkeyup = function () { document.getElementById( 'count-' + i ).innerHTML = (length - this.value.length); }; }
-
Always Helping about 3 years@Wracker you can use
on('input')
to get the counter update while holding down any key