Count and display number of characters in a textbox using Javascript

<script type="text/javascript">
function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
</script>

<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.

Plain Javascript.


You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
    var cs = $(this).val().length;
    $('#characters').text(cs);
}

UPDATE: jsFiddle (by Dreami)

UPDATE 2: Updating to include keydown for long presses.


This is my preference:

<textarea></textarea>         
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>

Then jquery block

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}

I would like to share my answer which i used in my project and it is working fine.

<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>

<script type='text/javascript'>
    $('#spnCharLeft').css('display', 'none');
    var maxLimit = 100;
    $(document).ready(function () {
        $('#<%= txtComments.ClientID %>').keyup(function () {
            var lengthCount = this.value.length;              
            if (lengthCount > maxLimit) {
                this.value = this.value.substring(0, maxLimit);
                var charactersLeft = maxLimit - lengthCount + 1;                   
            }
            else {                   
                var charactersLeft = maxLimit - lengthCount;                   
            }
            $('#spnCharLeft').css('display', 'block');
            $('#spnCharLeft').text(charactersLeft + ' Characters left');
        });
    });
</script>

Source: URL