dwinnbrown
dwinnbrown

Reputation: 3999

Javascript - Display remaining characters of text area

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?

Upvotes: 6

Views: 5924

Answers (3)

Heretic Sic
Heretic Sic

Reputation: 406

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));
    }
});

Upvotes: 0

James Craig
James Craig

Reputation: 6854

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.

Upvotes: 2

Rajesh
Rajesh

Reputation: 24915

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>

Upvotes: 2

Related Questions