Javascript 使用 jquery 在 textarea 中的最大字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5292235/
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-23 16:30:49  来源:igfitidea点击:

Max characters in textarea with jquery

javascriptjqueryvalidationtextarea

提问by Bill

I have the following code, and I'm kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left. Once you get to the max characters I want to stop allowing characters to be entered, or delete all the characters that were entered so there are only 10 characters in the text area. I know I have to put the code where it says alert("LONG");but I'm not quite sure what.

我有以下代码,但我有点不知道下一步该做什么。这个想法是当您在文本区域中输入文本时,计数器会告诉您剩余的字符数。一旦达到最大字符数,我想停止允许输入字符,或者删除所有输入的字符,以便文本区域中只有 10 个字符。我知道我必须把代码放在它说的地方,alert("LONG");但我不太确定是什么。

var maxLen = 10;
        console.log("Start");
        $('#send-txt').keyup(function(){
            var Length = $("#send-txt").val().length;
            var AmountLeft = maxLen - Length;
            $('#txt-length-left').html(AmountLeft);
            if(Length >= maxLen){
                alert("LONG");
            }



        });

回答by daprezjer

All of these answers are a bit odd in that they try to do a little too much. A simpler and visually more pleasing way (because it shows the text quickly being cut off) - and with with less oddities that the previous example (note how it overwrites the final key?) - is to simply cut off the number of characters on keyUp to the number that's allowed.

所有这些答案都有些奇怪,因为他们试图做得太多。一种更简单且视觉上更令人愉悦的方式(因为它显示文本很快被截断) - 并且与前面的示例相比没有那么奇怪(注意它如何覆盖最终键?) - 是简单地截断 keyUp 上的字符数到允许的数量。

        var textlimit = 400;

        $('textarea').keyup(function() {
            var tlength = $(this).val().length;
            $(this).val($(this).val().substring(0, textlimit));
            var tlength = $(this).val().length;
            remain = textlimit - parseInt(tlength);
            $('#remain').text(remain);
         });    

Note that this then also works for pasting in text, as some of the examples above don't.

请注意,这也适用于粘贴文本,因为上面的一些示例没有。

Example here: http://jsfiddle.net/PzESw/5/

这里的例子:http: //jsfiddle.net/PzESw/5/

回答by Hussein

Here it goes. Anything beyond character limit will be removed.

就到这里了。任何超出字符限制的内容都将被删除。

$('textarea').keypress(function(e) {
    var tval = $('textarea').val(),
        tlength = tval.length,
        set = 10,
        remain = parseInt(set - tlength);
    $('p').text(remain);
    if (remain <= 0 && e.which !== 0 && e.charCode !== 0) {
        $('textarea').val((tval).substring(0, tlength - 1));
        return false;
    }
})

Check working example at http://jsfiddle.net/JCehq/1/

http://jsfiddle.net/JCehq/1/检查工作示例

回答by Steve Claridge

Returning false and using .keypress() instead of .keyup() stops input once the length has been reached. Here's the example in a jsFiddle:

一旦达到长度,返回 false 并使用 .keypress() 而不是 .keyup() 停止输入。这是 jsFiddle 中的示例:

http://jsfiddle.net/p43BH/1/

http://jsfiddle.net/p43BH/1/

Updated to allow backspace.

更新以允许退格。

回答by user3460837

Got it with this:

明白了这个:

$("#div_id").prop('maxlength', '80');

I really dont know if there's something wrong with this solution, but it worked for me.

我真的不知道这个解决方案是否有问题,但它对我有用。

回答by Mark Hildreth

A simple way to do this is to set the text in the textarea to a substring of the full amount. You can find an example here:

一个简单的方法是将 textarea 中的文本设置为全量的子字符串。你可以在这里找到一个例子:

http://www.mediacollege.com/internet/javascript/form/limit-characters.html

http://www.mediacollege.com/internet/javascript/form/limit-characters.html

回答by Martin Jespersen

If you change your js to look like this it should work for you:

如果您将 js 更改为如下所示,它应该适合您:

var $txtLenLeft = $('#txt-length-left'); // lets cache this since it isn't changing
$('#send-txt').keydown(function(e) { //take the event argument
   var Length = $(this).val().length; // lets use 'this' instead of looking up the element in the DOM
   var AmountLeft = maxLen - Length;
   $txtLenLeft.html(AmountLeft);
   if(Length >= maxLen && e.keyCode != 8){ // allow backspace
      e.preventDefault(); // cancel the default action of the event
   }
});

You can see a working example here: http://jsfiddle.net/aP5sK/2/

你可以在这里看到一个工作示例:http: //jsfiddle.net/aP5sK/2/

回答by commonpike

ehm, textarea maxlength is a valid attribute in html5 ? not supported in ie9, thats all.

嗯,textarea maxlength 是 html5 中的有效属性吗?ie9 不支持,仅此而已。

w3nerds http://www.w3.org/TR/html-markup/textarea.html#textarea.attrs.maxlength

w3nerds http://www.w3.org/TR/html-markup/textarea.html#textarea.attrs.maxlength

w3fools http://www.w3schools.com/tags/att_textarea_maxlength.asp

w3fools http://www.w3schools.com/tags/att_textarea_maxlength.asp

回答by Mika T?htinen

Here's a solution using HTML5 data attribute to automatically bind to all needed textareas:

这是一个使用 HTML5 数据属性自动绑定到所有需要的文本区域的解决方案:

$('textarea[data-max-length]').live('keypress', function(e) {
    if (String.fromCharCode(e.charCode || e.keyCode).match(/\S/) && $(this).val().length >= $(this).attr('data-max-length')) {
        e.preventDefault();
    }
});

回答by Andrew Plank

I know this is a little late, but I just had to figure this out, too. I had to get it to work with UTF8 byte-lengths, and allow certain keypresses. Here's what I came up with:

我知道这有点晚了,但我也必须弄清楚这一点。我必须让它使用 UTF8 字节长度,并允许某些按键。这是我想出的:

checkContent = function (event) {

    var allowedKeys = [8,46,35,36,37,38,39,40];
    var contentLength = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    var charLength = lengthInUtf8Bytes(String.fromCharCode(event.charCode));

    if (charLength + contentLength > 20) {

        if(jQuery.inArray(event.keyCode, allowedKeys) == -1) {
            event.preventDefault();
        } 
    }
}

countLength = function(event) {

    var len = lengthInUtf8Bytes(jQuery(event.currentTarget).val());
    jQuery('#length').html(len);
}


lengthInUtf8Bytes = function(str) {
    var m = encodeURIComponent(str).match(/%[89ABab]/g);
    return str.length + (m ? m.length : 0);
}

jQuery(function(){jQuery("#textarea").keypress(function(event){checkContent(event)}).keyup(function(event){countLength(event)})});

You need to have a textarea with id #textarea and an element to display the current length with id #length.

你需要有一个id为#textarea的textarea和一个id为#length的元素来显示当前的长度。

The keypress event determines whether or not to allow the keypress. The keyup event counts the size of the data in the field after the keypress is allowed/prevented.

keypress 事件决定是否允许按键。keyup 事件计算允许/阻止按键后字段中数据的大小。

This code works with the following keys: home, end, pagedown, pageup, backspace, delete, up, down, left and right. It doesn't deal with pasting from the clipboard.

此代码使用以下键:home、end、pagedown、pageup、backspace、delete、up、down、left 和 right。它不处理从剪贴板粘贴。

Hope someone finds it useful!

希望有人觉得它有用!

回答by Halfstop

Relying on keypress, keydown, keyup is a flawed solution because a user can copy and paste data into the textarea without pressing any keys.

依赖于 keypress、keydown、keyup 是一个有缺陷的解决方案,因为用户可以在不按任何键的情况下将数据复制和粘贴到 textarea 中。

To limit the length of text in a textarea with javascript regardless of how the data gets in there you must rely on a setInterval timer instead.

要使用 javascript 限制 textarea 中文本的长度,而不管数据如何进入,您必须依赖 setInterval 计时器。

setInterval(function() {
if ($('#message').val().length > 250) {
    $('#message').val($('#message').val().substring(0, 250));
}}, 500);

Obviously, I'm assuming you have an id of message assigned to your textarea.

显然,我假设您有一个分配给 textarea 的消息 ID。