Textarea Character Count using JavaScript

Ilan Biala picture Ilan Biala · Dec 29, 2012 · Viewed 12.1k times · Source

I am implementing a character count for my form's textarea field. I have jQuery currently counting and writing my character statement using this code:

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

However, I would like to know what is wrong with my JavaScript:

var textarea = document.forms["form"].elements.textarea;

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

function textareaLengthCheck(textarea) {
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
}

The variable declaration and the event listener are in a jQuery document ready function. I am not sure what I am doing wrong for my event listener or function then.

Thanks

Answer

wazz3r picture wazz3r · Dec 29, 2012

The variable textarea is not present in the function's scope, you can refere to it with the this keyword

function textareaLengthCheck() {
    var length = this.value.length;
    var charactersLeft = 500 - length;
    var count = document.getElementById('count');
    count.innerHTML = "Characters left: " + charactersLeft;
}