计数textarea字符 [英] Count textarea characters

查看:138
本文介绍了计数textarea字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为网站上的textarea开发一个字符数。现在,它说NaN,因为它似乎没有找到字段中有多少个字符的长度,在开始时它是0,因此数字应该是500.在Chrome开发人员工具的控制台中,不会出现错误。我的所有代码都在网站上,我甚至试图使用jQuery作为textarea字段的字符数,但没有任何效果。

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.

请告诉我做了什么我在我的contact.js文件中的jQuery和JavaScript代码都有问题。

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;
}


推荐答案

$("#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));
});

或者,您也可以在不使用 jQuery 使用下面的代码。 (Thanks @Niet)

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);
};

这篇关于计数textarea字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆