Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

javascript - Count textarea characters

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);
    });a€?*/

    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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$("#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);
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...