使用 jquery 或其他方式对 textarea 中的可用空间进行倒计时?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1250748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:00:10  来源:igfitidea点击:

Countdown available spaces in a textarea with jquery or other?

jquerytextmax

提问by JasonDavis

I have a few areas on my site where I need to limit text input to X amount of characters and it's nice to show a number of spaces left while a user types in, like twitter does.

我的网站上有几个区域需要将文本输入限制为 X 个字符,并且在用户输入时显示一些剩余的空格是很好的,就像 twitter 那样。

I found this jquery plugin; jquery max-length plugin

我找到了这个 jquery 插件; jquery 最大长度插件

It does just what I need but it seems kind of like overkill, I am not sure the filesize but it looks like a lot of lines of code for such a simple task, do you think I would be better off using a non-jquery method? The reason I was thinking jquery was the way to go is because jquery is already included into all my pages UPDATE;

它正是我需要的,但似乎有点矫枉过正,我不确定文件大小,但对于这样一个简单的任务,它看起来像很多行代码,你认为我最好使用非 jquery 方法吗? ? 我认为 jquery 是要走的路的原因是因为 jquery 已经包含在我所有的页面 更新中;

I just found this non-jquery method that does the exact same thing is is way smaller footprint, so would this be the better method?

我刚刚发现这种完全相同的非 jquery 方法占用的空间更小,所以这会是更好的方法吗?

<script language="javascript" type="text/javascript">
function limitText(limitField, limitCount, limitNum) {
   if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
   } else {
    limitCount.value = limitNum - limitField.value.length;
   }
}
</script>

You have 
<input readonly type="text" name="countdown" size="3" value="1000">
characters left.

回答by deceze

Very simple in jQuery:

在 jQuery 中非常简单:

<textarea id="myTextarea"></textarea>
<p id="counter"></p>

<script type="text/javascript">
$('#myTextarea').keyup(function () {
    var left = 200 - $(this).val().length;
    if (left < 0) {
        left = 0;
    }
    $('#counter').text('Characters left: ' + left);
});
</script>

Substitute the 200 by whatever your limit is.

用你的极限来代替 200。

Note this does not limit the actual text input, it just counts down. You need to check server-side for the input length, this is just a visual helper.

请注意,这并不限制实际的文本输入,它只是倒计时。您需要检查服务器端的输入长度,这只是一个视觉助手。

As an aside, I don't think you even should try to limit the input length by denying any input when the limit is reached. It's a pain in the rear usability-wise and can't be relied upon anyway. A simple countdown and server-side checking is the best option IMHO.

顺便说一句,我认为您甚至不应该尝试通过在达到限制时拒绝任何输入来限制输入长度。这是后方可用性方面的痛苦,无论如何都不能依赖。简单的倒计时和服务器端检查是恕我直言的最佳选择。

回答by gordon

Sometimes you need to have more than one text area and want them addressed individually without having to code for each. This code dynamically adds the chars remaining to any having a maxLength attribute...

有时您需要有多个文本区域,并希望它们单独寻址,而不必为每个区域编码。此代码动态地将剩余的字符添加到任何具有 maxLength 属性的字符...

<script type="text/javascript">
$(document).ready(function(){
    $('textarea[maxLength]').each(function(){
        var tId=$(this).attr("id");
        $(this).after('<br><span id="cnt'+tId+'"></span>');
        $(this).keyup(function () {
            var tId=$(this).attr("id");
            var tMax=$(this).attr("maxLength");//case-sensitive, unlike HTML input maxlength
            var left = tMax - $(this).val().length;
            if (left < 0) left = 0;
            $('#cnt'+tId).text('Characters left: ' + left);
        }).keyup();
    });
});
</script>
<textarea id="myTextarea" maxLength="200">Initial text lorem ipsum blah blah blah</textarea><br><br>
<textarea id="mySecondTextarea" maxLength="500"></textarea><br><br>
<textarea id="textareaWithoutCounter"></textarea>

回答by Ryan McGeary

I've used Aaron Russell's simply countable jQuery pluginwith success

我已经成功使用了 Aaron Russell 的简单可数的 jQuery 插件

Simple usage:

简单用法:

$('#my_textarea').simplyCountable();

Advanced usage:

高级用法:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});

回答by Mujahid Ali

 var max = 140;
        $("#spn").html(max+"  Remaining");
        $("#textarea").keyup(function () {
            var lenght1 = $("#textarea").val().length;
            var remaining = max - lenght1;
            $("#spn").html(remaining + "  Remaining");
            if (remaining < 0) { $("#spn").css('opacity', '0.4').css('color', 'red'); $("#comment").attr('disabled', 'disabled'); } else { $("#spn").css('opacity', '1').css('color', 'black'); $("#comment").removeAttr('disabled'); }
            if (remaining < 10) { $("#spn").css('color', 'red'); } else { $("#spn").css('color', 'black'); }

        });

回答by Raghav

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function()
        {
            $('#TestId').keyup(function(e)
            {
                var maxLength = 100;
                var textlength = this.value.length;
                if (textlength >= maxLength)
                {
                    $('#charStatus').html('You cannot write more then ' + maxLength + ' characters!');
                    this.value = this.value.substring(0, maxLength);
                    e.preventDefault();
                }
                else
                {
                    $('#charStatus').html('You have ' + (maxLength - textlength) + ' characters left.');
                }
            });
        });
    </script>
</head>
<body>
    <textarea id="TestId" cols="20" rows="8"></textarea><br />
    (Maximum characters: 100)<br />
    <span id="charStatus"></span>   
</body>
</html>

回答by Falkayn

I used jQuery and the answerby deceze and then tweaked it to give me a twitter-style countdown so that users could see by how much they had gone over and adjust their text accordingly. I also put it into its own function so I could call it from another function that sometimes populated the textarea automatically:

我使用了 jQuery 和deceze的答案,然后对其进行了调整,为我提供了一个 twitter 风格的倒计时,以便用户可以看到他们已经完成了多少并相应地调整他们的文本。我还把它放到了它自己的函数中,这样我就可以从另一个有时自动填充 textarea 的函数调用它:

    function reCalcToText() {
        var left = 200 - $('.toText').val().length;
        if (left < 0) {
            $('#counter').text(left);
            $('#counter').addClass("excess");
        } else {
            $('#counter').text(left);
            $('#counter').removeClass();
        }
    }
    function onReady() {
                  $('#<%= toText.ClientID %>').keyup(function() {
            reCalcToText();
        });
    };

回答by Christoffer

So I took @deceze version and added a bit of trick to make it:

所以我采用了@deceze 版本并添加了一些技巧来制作它:

  • show always and not only when the user starts typing,
  • show minus when the limit is over, and
  • add class - to color the text - when it is over the limit (extra css is needed for this of course)

    $(document).ready(function(){
        var left = 200
        $('#field_counter').text('Characters left: ' + left);
    
            $('#id_description').keyup(function () {
    
            left = 200 - $(this).val().length;
    
            if(left < 0){
                $('#field_counter').addClass("overlimit");
            }
            if(left >= 0){
                $('#field_counter span').removeClass("overlimit");
            }
    
            $('#field_counter').text('Characters left: ' + left);
        });
    });
    
  • 始终显示,而不仅仅是在用户开始输入时显示,
  • 当限制结束时显示减号,并且
  • 添加类 - 为文本着色 - 当超过限制时(当然需要额外的 css)

    $(document).ready(function(){
        var left = 200
        $('#field_counter').text('Characters left: ' + left);
    
            $('#id_description').keyup(function () {
    
            left = 200 - $(this).val().length;
    
            if(left < 0){
                $('#field_counter').addClass("overlimit");
            }
            if(left >= 0){
                $('#field_counter span').removeClass("overlimit");
            }
    
            $('#field_counter').text('Characters left: ' + left);
        });
    });
    

For anyone needing the same as me :)

对于任何需要和我一样的人:)

回答by trainer

Keep in mind that you have to account for NewLines being 2 characters.
I built upon the solutions provided here to the below code which accounts for new lines.

请记住,您必须考虑到 NewLines 为 2 个字符。
我在此处提供的解决方案的基础上构建了以下代码,该代码占新行。

function DisplayCharactersLeft(idOfInputControl) {
    var maxNumberOfCharacters = $("#" + idOfInputControl).attr("maxLength");

    $("#" + idOfInputControl).on("input", function () {
        var currentText = $(this).val();
        var numberOfNewLines = GetNumberOfNewLines(currentText);

        var left = maxNumberOfCharacters - (currentText.length + numberOfNewLines);
        if (left < 0) { left = 0; }
        $("#" + idOfInputControl + "CharactersLeftCounter").text("Characters left: " + left);
    });

}    

function GetNumberOfNewLines(text) {

    var newLines = text.match(/(\r\n|\n|\r)/g);
    var numberOfNewLines = 0;
    if (newLines != null) {
        numberOfNewLines = newLines.length;
    }
    return numberOfNewLines;
}

回答by bryan

Using jQuery, assuming that you have a textarea with id fieldthat you wish to limit to 100 characters, and another element with id chars-remainingto display the number of available characters:

使用 jQuery,假设您有一个带有 id字段的文本区域,您希望将其限制为 100 个字符,以及另一个带有 id chars-remaining 的元素来显示可用字符的数量:

var max = 100;
$('#field').keyup(function() {
    if($(this).val().length > max) {
        $(this).val($(this).val().substr(0, max));
    }
    $('#chars-remaining').html((max - $(this).val().length) + ' characters remaining');
});