6

So I have set the maxlength of my textarea to be 200 and I would like to display a nice countdown function that shows how many characters they have left as they are typing.

My HTML is as follows:

<tr>
    <th width="20%" scope="row" valign="top">Description<div id="characters-left"></div></th>
    <td width="80%"><textarea id="text-area" style="width: 48%" name="poll-description" value="" maxlength="200"></textarea></td>
</tr>

And the JS that I am trying to do it with is like this:

<script>
    window.onload = textareaLengthCheck();

    function textareaLengthCheck() {
    var textArea = document.getElementById('text-area').value.length;
    var charactersLeft = 200 - textArea;
    var count = document.getElementById('characters-left');
    count.innerHTML = "Characters left: " + charactersLeft;
}
</script>

I would rather do this with vanilla javascript as opposed to jQuery if possible. Any ideas?

dwinnbrown
  • 3,789
  • 9
  • 35
  • 60

3 Answers3

2

As I have commented, function textareaLengthCheck should be a key event. Following code depicts same:

function textareaLengthCheck(el) {
  var textArea = el.value.length;
  var charactersLeft = 200 - textArea;
  var count = document.getElementById('lblRemainingCount');
  count.innerHTML = "Characters left: " + charactersLeft;
}
<textarea id="txtInput" onkeypress="textareaLengthCheck(this)"></textarea>
<p id="lblRemainingCount"></p>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • the event listnener **onkeypress** will not fire when backspace is clicked, and for that reason the remaining characters will be incorrect if the user deletes wat he has been typing. Replace it with **onkeydown** instead – Coding Sniper Jan 28 '22 at 11:10
2

You can bind event listeners for keyup and keydown like this.

var textarea = document.getElementById('text-area');

textarea.addEventListener('keyup', textareaLengthCheck, false);
textarea.addEventListener('keydown', textareaLengthCheck, false);

See this JSFiddle.

Or you can do what Rajesh suggested using HTML5.

Community
  • 1
  • 1
Enijar
  • 6,387
  • 9
  • 44
  • 73
  • 1
    use instead of 'keyup' and 'keydown' the 'input' event, if you Copy&Paste a Text on input or textareas the Event 'keyup' and 'keydown' don't fired! And you need only one eventListener :) – MaZzIMo24 Oct 15 '22 at 11:44
0

On jquery, you can do this

$('#text-area').keyup(function() {
    if ($('#text-area').text().length < 200) {
        $('#characters-left').text('Characters left: ' + (200 - $('#text-area').text().length));
    }
});
Heretic Sic
  • 364
  • 2
  • 9