44

I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.

Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.

$(document).ready(function() {
    var tel1 = document.forms["form"].elements.tel1;
    var tel2 = document.forms["form"].elements.tel2;
    var textarea = document.forms["form"].elements.textarea;
    var clock = document.getElementById("clock");
    var count = document.getElementById("count");

    tel1.addEventListener("keyup", function (e){
        checkTel(tel1.value, tel2);
    });

    tel2.addEventListener("keyup", function (e){
        checkTel(tel2.value, tel3);
    });

    /*$("#textarea").keyup(function(){
        var length = textarea.length;
        console.log(length);
        var charactersLeft = 500 - length;
        console.log(charactersLeft);
        count.innerHTML = "Characters left: " + charactersLeft;
        console.log("Characters left: " + charactersLeft);
    });​*/

    textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});

function checkTel(input, nextField) {
    if (input.length == 3) {
        nextField.focus();
    } else if (input.length > 0) {
        clock.style.display = "block";
    } 
}

function textareaLengthCheck(textarea) {
    var length = textarea.length;
    var charactersLeft = 500 - length;
    count.innerHTML = "Characters left: " + charactersLeft;
}
Ilan Biala
  • 3,093
  • 5
  • 32
  • 45

11 Answers11

88
$("#textarea").keyup(function(){
  $("#count").text($(this).val().length);
});

The above will do what you want. If you want to do a count down then change it to this:

$("#textarea").keyup(function(){
  $("#count").text("Characters left: " + (500 - $(this).val().length));
});

Alternatively, you can accomplish the same thing without jQuery using the following code. (Thanks @Niet)

document.getElementById('textarea').onkeyup = function () {
  document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
Andrew Hubbs
  • 8,842
  • 8
  • 43
  • 70
  • I want it to say "Characters left: xxx" xxx being a number 500 or lower. – Ilan Biala Dec 29 '12 at 22:26
  • 1
    Updated to say what you wanted. – Andrew Hubbs Dec 29 '12 at 22:29
  • exactly that and for some reason it said NaN after I typed something, lemme try your snippet. – Ilan Biala Dec 29 '12 at 22:31
  • Cool, yours works, I think I missed the last quotes for the string part of the text. Thanks. – Ilan Biala Dec 29 '12 at 22:31
  • 8
    Replace code with `document.getElementById('textarea').onkeyup = function() {document.getElementById('count').innerHTML = "Characters left: "+(500-this.value.length);};` and it will run about a hundred times faster ;) – Niet the Dark Absol Dec 29 '12 at 23:54
  • @NiettheDarkAbsol Why would that be faster? – Ilan Biala Jan 25 '14 at 03:50
  • 1
    for this operation, I think it's only 1-2 ms we're talking about here...so I'm not too concerned. – Ilan Biala Jan 25 '14 at 19:06
  • @NiettheDarkAbsol Please format your code correctly for SO, so that others who may be interested can clearly follow. – Cassandra Feb 09 '15 at 03:49
  • @NiettheDarkAbsol well it doesn't work as presented, for starters. Code should have four spaces before each line so it formats clearly. Read the notes below the comment box next time you're entering a comment. It's right there. And to me, it looks like your code is partial and not full. As it is it does not function. – Cassandra Feb 09 '15 at 07:43
  • 2
    @Cassandra You cannot do code blocks in comments. [My code works fine](http://jsfiddle.net/vo70g24x/) – Niet the Dark Absol Feb 09 '15 at 13:55
  • @NiettheDarkAbsol Point taken re not being able to do code blocks in comments. Perhaps it would have been better suited as an answer anyway. :) Your code breaks on the page I've tried to use it on, however I've another answer from here that I am modifying and implementing now. Would have liked to have used yours, but wasn't presented well at the time. – Cassandra Feb 09 '15 at 14:10
33

⚠️ The accepted solution is outdated.

Here are two scenarios where the keyup event will not get fired:

  1. The user drags text into the textarea.
  2. The user copy-paste text in the textarea with a right click (contextual menu).

Use the HTML5 input event instead for a more robust solution:

<textarea maxlength='140'></textarea>

JavaScript (demo):

const textarea = document.querySelector("textarea");

textarea.addEventListener("input", event => {
    const target = event.currentTarget;
    const maxLength = target.getAttribute("maxlength");
    const currentLength = target.value.length;

    if (currentLength >= maxLength) {
        return console.log("You have reached the maximum number of characters.");
    }

    console.log(`${maxLength - currentLength} chars left`);
});

And if you absolutely want to use jQuery:

$('textarea').on("input", function(){
    var maxlength = $(this).attr("maxlength");
    var currentLength = $(this).val().length;

    if( currentLength >= maxlength ){
        console.log("You have reached the maximum number of characters.");
    }else{
        console.log(maxlength - currentLength + " chars left");
    }
});
Etienne Martin
  • 6,703
  • 2
  • 29
  • 40
13
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);

You are calling textareaLengthCheck and then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:

textarea.addEventListener("keypress",textareaLengthCheck,false);

Aside from that:

var length = textarea.length;

textarea is the actual textarea, not the value. Try this instead:

var length = textarea.value.length;

Combined with the previous suggestion, your function should be:

function textareaLengthCheck() {
    var length = this.value.length;
    // rest of code
};
Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
11

Here is simple code. Hope it is working

$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');

$('#textarea').keyup(function() {
    var text_length = $('#textarea').val().length;
    var text_remaining = text_max - text_length;

    $('#textarea_feedback').html(text_remaining + ' characters remaining');
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
Shafiqul Islam
  • 5,065
  • 1
  • 26
  • 39
  • it does not update the counter while holding down any key. So I quess it would also worth adding another handler for $("#textarea")keydown( .. ) – Wracker Aug 25 '14 at 13:34
  • @Wracker you can use `on('input')` to get the counter update while holding down any key – Always Helping Apr 20 '21 at 05:31
4

This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.

<DEMO>

var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
  document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
 maxlength="500"></textarea>
<span id="count"></span>
Kurenai Kunai
  • 1,786
  • 2
  • 10
  • 22
1

For those wanting a simple solution without jQuery, here's a way.

textarea and message container to put in your form:

<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>

JavaScript:

<script>
function count_it() {
    document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>

The script counts the characters initially and then for every keystroke and puts the number in the counter span.

Martin

  • Simple and elegant. Thank you. jQuery is fine but I really wish there were more pure javascript solutions like yours. – Lara Apr 29 '18 at 07:54
1

I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attribute because of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the input and propertychange events. The following takes newline characters into account and accurately calculates the length of a textarea.

$(function() {
  $("#myTextArea").on("input propertychange", function(event) {
    var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;

    $("#counter").html(curlen);
  });
});

$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
Nielsvh
  • 1,027
  • 1
  • 17
  • 30
0

var maxchar = 10;
$('#message').after('<span id="count" class="counter"></span>');
$('#count').html(maxchar+' of '+maxchar);
$('#message').attr('maxlength', maxchar);
$('#message').parent().addClass('wrap-text');
$('#message').on("keydown", function(e){
 var len =  $('#message').val().length;
 if (len >= maxchar && e.keyCode != 8)
     e.preventDefault();
 else if(len <= maxchar && e.keyCode == 8){
  if(len <= maxchar && len != 0)
      $('#count').html(maxchar+' of '+(maxchar - len +1));
     else if(len == 0)
      $('#count').html(maxchar+' of '+(maxchar - len));
 }else
   $('#count').html(maxchar+' of '+(maxchar - len-1)); 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="message" name="text"></textarea>
0
    $(document).ready(function(){ 
    $('#characterLeft').text('140 characters left');
    $('#message').keydown(function () {
        var max = 140;
        var len = $(this).val().length;
        if (len >= max) {
            $('#characterLeft').text('You have reached the limit');
            $('#characterLeft').addClass('red');
            $('#btnSubmit').addClass('disabled');            
        } 
        else {
            var ch = max - len;
            $('#characterLeft').text(ch + ' characters left');
            $('#btnSubmit').removeClass('disabled');
            $('#characterLeft').removeClass('red');            
        }
    });    
});
PK-1825
  • 1,219
  • 13
  • 30
0

They say IE has issues with the input event but other than that, the solution is rather straightforward.

ta = document.querySelector("textarea");
count = document.querySelector("label");

ta.addEventListener("input", function (e) {
  count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
Ronnie Royston
  • 11,959
  • 5
  • 57
  • 72
0

This solution will respond to keyboard and mouse events, and apply to initial text.

    $(document).ready(function () {
        $('textarea').bind('input propertychange', function () {
            atualizaTextoContador($(this));
        });

        $('textarea').each(function () {
            atualizaTextoContador($(this));
        });
    });

    function atualizaTextoContador(textarea) {
        var spanContador = textarea.next('span.contador');
        var maxlength = textarea.attr('maxlength');
        if (!spanContador || !maxlength)
            return;
        var numCaracteres = textarea.val().length;
        spanContador.html(numCaracteres + ' / ' + maxlength);
    }
    span.contador {
        display: block;
        margin-top: -20px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>
Junior
  • 134
  • 2
  • 8