I want to have a text area which shows how much i wrote in it and displays it on the bottom right of the textarea(inside the textbox ) out of the max length of the value. cant find how to do so. Thanks.
Asked
Active
Viewed 3,043 times
-4
-
You could at least try something, whatever possibile answer here : http://stackoverflow.com/questions/5371089/count-characters-in-textarea – steo Jul 18 '13 at 10:12
-
What have you already tried? – BenM Jul 18 '13 at 10:12
-
Have you even bothered googling it ? http://bit.ly/194xTGb – Patsy Issa Jul 18 '13 at 10:12
-
I guess it wasn't that urgent, then... – BenM Jul 18 '13 at 22:47
2 Answers
1
You can achieve this using jQuery with the following simple code:
var theCounter = $('#textareaLength'),
textarea = $('#myTextarea'),
maxLength = textarea.attr('length');
theCounter.text('0 / '+maxLength);
theCounter.css({
'top': (textarea.offset().top + textarea.height()) - theCounter.height(),
'left': (textarea.offset().left + textarea.width()) - theCounter.width()
});
textarea.on('keydown', function() {
var theLength = $(this).val().length;
theCounter.text($(this).val().length+' / '+maxLength)
.css({
'left': (textarea.offset().left + textarea.width()) - theCounter.width()
});
});
Obviously you'll need to put in some logic to prevent any further action from occuring if the max length is met, but that should be pretty self-explanatory.
I've put together a jsFiddle for you.
-1
Here is a function you can use
JAVASCRIPT:
function CountWords(s) {
var maxChars = 2048;
if (s.value.length > maxChars) {
s.value = s.value.substring(0, maxChars);
}
else {
$($(s).parent()).find("#words").html((maxChars - s.value.length) + " characters left.");
}
}
HTML:
<textarea onkeyup="CountWords(this)" id="txtBody" rows="50" cols="10"
></textarea>
<span id="words" style="width: 120px; color:Gray; display: block; float: left; margin: 5px; line-height: 27px;">
2048 characters left.</span>
you can just change the numbers to how many letter limit you want.

Jeandre Pentz
- 992
- 2
- 9
- 20
-
1You're using a combination of vanilla JavaScript and jQuery in your answer - it might be worth mentioning that. Also, it's 2013; please don't recommend intrusive event handlers. – BenM Jul 18 '13 at 10:25