javascript 如何使用 maxlength 在 textarea 中阻止进一步输入

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

How can I block further input in textarea using maxlength

javascriptjquerymaxlength

提问by user342391

I have a textarea that I want to block input on if the entered characters reaches a max-length.

我有一个文本区域,如果输入的字符达到最大长度,我想阻止输入。

I currently have a Jquery script for the textbox that calculates the characters entered and want to add something that will block input in the textarea once 150 characters are entered.

我目前有一个用于计算输入字符的文本框的 Jquery 脚本,并希望添加一些内容,一旦输入 150 个字符,就会在文本区域中阻止输入。

I have tried using max-length plugins in conjunction with my script but they don't seem to work. Help is appreciated.

我曾尝试将 max-length 插件与我的脚本结合使用,但它们似乎不起作用。帮助表示赞赏。

CURRENT CODE

当前代码

(function($) {
    $.fn.charCount = function(options){
        // default configuration properties
        var defaults = {    
            allowed: 150,       
            warning: 25,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: '',
            container: undefined // New option, accepts a selector string
        }; 

        var options = $.extend(defaults, options); 

        function calculate(obj,$cont) {
              // $cont is the container, now passed in instead.
            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $cont.addClass(options.cssWarning);
            } else {
                $cont.removeClass(options.cssWarning);
            }
            if(available < 0){
                $cont.addClass(options.cssExceeded);
            } else {
                $cont.removeClass(options.cssExceeded);
            }
            $cont.html(options.counterText + available);
        };

        this.each(function() {
         // $container is the passed selector, or create the default container
            var $container = (options.container)
                    ? $(options.container)
                        .text(options.counterText)
                        .addClass(options.css)
                    : $('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>').insertAfter(this);
            calculate(this,$container);
            $(this).keyup(function(){calculate(this,$container)});
            $(this).change(function(){calculate(this,$container)});
        });

    };
})(jQuery);

回答by Robert

Have you tried ?the maxlength attribute? That will block input once the character limit is reached.

你试过吗? maxlength 属性?一旦达到字符限制,这将阻止输入。

<textarea maxlength='150'></textarea>?????????????????????????? // Won't work
<input type='text' maxlength='150' />

EditIt appears that maxlength for a textarea works in Chrome, but not in other browsers, my bad. Well, another approach would just be to monitor keydown events and if length>150, return false/preventDefault/however you want to stop the default action. You'd still want allow backspace and enter however, so monitor keycode as well.

编辑似乎 textarea 的 maxlength 在 Chrome 中有效,但在其他浏览器中无效,我的错。好吧,另一种方法就是监视 keydown 事件,如果长度> 150,则返回 false/preventDefault/但是您想停止默认操作。但是,您仍然希望允许退格和输入,因此还要监视键码。

$('#yourTextarea').keydown(function(e) {
    if (this.value.length > 150) 
        if ( !(e.which == '46' || e.which == '8' || e.which == '13') ) // backspace/enter/del
            e.preventDefault();
});

回答by Tim Down

You're much better off not trying to prevent the user from typing in too many characters and instead showing a counter and only enforcing the character limit when the user tries to submit. The comment boxes Stack Overflow are a decent example. It's both easier technically and more importantly better for the user to do it this way: it's really irritating not to be able to type/paste/drag text into a textarea even if you know there's a character limit.

您最好不要试图阻止用户输入太多字符,而是显示一个计数器并仅在用户尝试提交时强制执行字符限制。评论框 Stack Overflow 是一个不错的例子。以这种方式在技术上更容易,更重要的是对用户来说更好:即使您知道有字符限制,也无法将文本键入/粘贴/拖动到文本区域中,这真的很令人恼火。

回答by DaveB

Textarea maxlength with Jqueryworks OK but probably doesn't solve the issue of pasting in larger amounts of text.

使用 Jquery 的 Textarea maxlength工作正常,但可能无法解决粘贴大量文本的问题。

PB Edit: Has since been updated here

PB 编辑:此后已在此处更新

回答by Abdllah

Try this code below i hope will work, remember to include jQuery library

试试下面的这段代码,我希望会起作用,记得包含 jQuery 库

<div class="texCount"></div>
<textarea class="comment"></textarea>

$(document).ready(function(){
    var text_Max = 200;      
    $('.texCount').html(text_Max+'Words');

    $('.comment').keyup(function(){        
        var text_Length = $('.comment').val().length;        
        var text_Remain = text_Max - text_Length;       
        $('.texCount').html(text_Remain + 'Words');

        $('.comment').keydown(function(e){         
            if(text_Remain == 0){
                e.preventDefault();
            }
        });
    });    
});

回答by PleaseStand

You can truncate the contents of the textarea if it is over 150 characters as described at http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/. I can see some issues with copy/pasting if that brings the text over the limit though.

http://web.enavu.com/daily-tip/maxlength-for-textarea-with-jquery/所述,您可以截断超过 150 个字符的 textarea 的内容。如果复制/粘贴使文本超过限制,我可以看到一些问题。