Jason PresleyJason Presley

Counting Characters in a Text Area

There are many times that you may want to count the number of characters in a text area and display that number to the users especially to show limits on text fields. This is very easily done with a little jQuery.

Depending if you want to show total character count or characters remaining there is a slight modification but generally the same. This first example is to show total characters entered into the field.

First is the HTML for the text area and the span to show the character count.

<textarea id="message"></textarea>
<span id="chars">0</span> total characters

The following jQuery will then count the characters and update the value of the span on each keystroke.

<script> $(function (){ $('#message').keyup(function (){ var length=$(this).val().length;
$('#chars').text(length);
});
})
</script>

If the text area has a limit and you want to display the remaining characters left there are just a few minor changes. First we are going to change the text of the span to show the REMAINING character count.

<textarea id="message"></textarea>
<span id="chars">500</span> characters left

Then the following jQuery will then count the characters, subtract them from the total amount possible and again update the value of the span on each keystroke.

<script> $(function (){ var maxLength=500;
$('#message').keyup(function (){ var length=$(this).val().length;
var length=maxLength - length;
$('#chars').text(length);
});
})
</script>
<< View All Posts