简体   繁体   English

计算文本区域字符

[英]Count textarea characters

I am developing a character count for my textarea on this website .我正在这个网站上为我的 textarea 开发字符数。 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.现在,它说NaN,因为它似乎找不到字段中有多少个字符的长度,开头是0,所以数字应该是500。在chrome开发人员工具的控制台中,没有错误发生。 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.我所有的代码都在网站上,我什至尝试使用 jQuery 和常规 JavaScript 来计算 textarea 字段的字符数,但似乎没有任何效果。

Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.请告诉我在我的contact.js 文件中的jQuery 和JavaScript 代码中我做错了什么。

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

Alternatively, you can accomplish the same thing without jQuery using the following code.或者,您可以使用以下代码在不使用jQuery的情况下完成相同的操作。 (Thanks @Niet) (感谢@Niet)

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

⚠️ The accepted solution is outdated. ⚠️ 接受的解决方案已过时。

Here are two scenarios where the keyup event will not get fired:以下是不会触发keyup事件的两种情况:

  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:改用 HTML5 input事件以获得更强大的解决方案:

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

JavaScript ( demo ): JavaScript(演示):

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:如果你绝对想使用 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");
    }
});
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);

You are calling textareaLengthCheck and then assigning its return value to the event listener.您正在调用textareaLengthCheck ,然后将其返回值分配给事件侦听器。 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. textarea是实际的文本区域,而不是值。 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
};

Here is simple code.这是简单的代码。 Hope it help you希望对你有帮助

 $(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>

This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.此代码从textareamaxlength属性中获取最大值,并随着用户键入而减小该值。

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

For those wanting a simple solution without jQuery, here's a way.对于那些想要一个没有 jQuery 的简单解决方案的人来说,这里有一个方法。

textarea and message container to put in your form: textarea 和消息容器放入您的表单:

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

JavaScript: 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马丁

I found that the accepted answer didn't exactly work with textarea s 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.我发现接受的答案并不完全适用于textarea ,原因是Chrome 中指出的原因,由于换行符和回车符,在具有 maxlength 属性的 textarea 中计数字符错误,如果您需要知道将占用多少空间,这一点很重要将信息存储在数据库中时。 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.此外,由于从剪贴板拖放和粘贴文本,keyup 的使用被贬低,这就是我使用inputpropertychange事件的原因。 The following takes newline characters into account and accurately calculates the length of a textarea .以下考虑换行符并准确计算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" />

 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>

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

They say IE has issues with the input event but other than that, the solution is rather straightforward.他们说 IE 的input事件有问题,但除此之外,解决方案相当简单。

 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>

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM