jQuery 如何防止用户在达到最大字符限制后在 textarea 中输入文本

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

How to prevent user to enter text in textarea after reaching max character limit

jquery

提问by Basit

I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code.

一旦达到最大字符限制,我想阻止用户在 textarea 中输入文本。发生了什么,当我达到最大限制然后我的文本区域滚动条移到顶部时,我以某种方式使用此代码阻止了这种情况。

jQuery(document).ready(function($) {
    $('textarea.max').keyup(function() {
        var $textarea = $(this);
        var max = 400;
        if ($textarea.val().length > max) {
            var top = $textarea.scrollTop();
            $textarea.val($textarea.val().substr(0, max));
            $textarea.scrollTop(top);

        }
    });
}); //end if ready(fn)

But i also want that after reaching max limit user unable to type anything in the textarea. Currently what happen that after reaching max limit if user press and hold the key, the characters are typing in the text area, although after releasing the button it come back to original text (i.e $textarea.val($textarea.val().substr(0, max)); ). But i want that once this condition become true

但我也希望在达到最大限制后用户无法在 textarea 中输入任何内容。目前,如果用户按住该键,达到最大限制后,字符会在文本区域中输入,但释放按钮后会返回原始文本(即 $textarea.val($textarea.val())。 substr(0, max)); )。但我希望一旦这种情况成为现实

if ($textarea.val().length > max) {

user unable to type anything. I want that cursor vanishes from the textarea. But if user remove some text then cursor also available for user to type input again. How can I do it?

用户无法输入任何内容。我希望光标从 textarea 中消失。但是如果用户删除一些文本,则光标也可供用户再次输入。我该怎么做?

回答by Rob W

The keyupevent fires after the default behaviour (populating text area) has occurred.

keyup事件在默认行为(填充文本区域)发生后触发。

It's better to use the keypressevent, and filter non-printable characters.

最好使用keypress事件,并过滤不可打印的字符。

Demo: http://jsfiddle.net/3uhNP/1/(with max length 4)

演示:http: //jsfiddle.net/3uhNP/1/(最大长度为 4)

jQuery(document).ready(function($) {
    var max = 400;
    $('textarea.max').keypress(function(e) {
        if (e.which < 0x20) {
            // e.which < 0x20, then it's not a printable character
            // e.which === 0 - Not a character
            return;     // Do nothing
        }
        if (this.value.length == max) {
            e.preventDefault();
        } else if (this.value.length > max) {
            // Maximum exceeded
            this.value = this.value.substring(0, max);
        }
    });
}); //end if ready(fn)

回答by KBN

<textarea maxlength="400"> </textarea>

Use the above code to limit the number of characters inserted in a text area, if you want to disable the textarea itself (ie, will not be able to edit afterwards) you can use javascript/jquery to disable it.

使用上面的代码来限制文本区域插入的字符数,如果你想禁用文本区域本身(即之后将无法编辑)你可以使用javascript/jquery来禁用它。

回答by Joseph Fizzy Beats

Keep it simple

把事情简单化

var max = 50;
$("#textarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
});

and add this in your html

并将其添加到您的 html 中

<textarea id="textarea" maxlength="50"></textarea>
<div id="count"></div>

view example

查看示例

回答by GuRu

You could directly give maxlengthto textareato disable itself. But, you want to showing appropriate message then use keyupevent for default behavior and textarealengthfor calculating charcter and display suitable message.

你可以直接给maxlengthtextarea禁用本身。但是,您希望显示适当的消息,然后将keyup事件用于默认行为和textarealength计算字符并显示合适的消息。

HTML

HTML

<div id="count"></div>
<textarea class="max"  maxlength="250" id="tarea"></textarea>
<div id="msg"></div>

jQuery

jQuery

$(function(){
    var max = parseInt($("#tarea").attr("maxlength"));
  $("#count").text("Characters left: " + max);
    $("#tarea").keyup(function(e){
        $("#count").text("Characters left: " + (max - $(this).val().length));
    if($(this).val().length==max)
        $("#msg").text("Limit Reached....");
        else
        $("#msg").text("");
    });
});

Demo Fiddle

演示小提琴

回答by ViPuL5

Just write this code in your Javascript file.. But Need to specify the 'maxlength' attribute with textarea. This will work for all textarea of a page.

只需在您的 Javascript 文件中编写此代码。但需要使用 textarea 指定“maxlength”属性。这将适用于页面的所有文本区域。

$('textarea').bind("change keyup input",function() {

        var limitNum=$(this).attr("maxlength");

        if ($(this).val().length > limitNum) {
            $(this).val($(this).val().substring(0, limitNum));
        }

    });

回答by arb

You could use thisplugin instead of trying to write your own. I've found that it works pretty well.

您可以使用插件而不是尝试编写自己的插件。我发现它工作得很好。

回答by Gus

For those already using ES2015 in your browsers, here's an implementation using some of the answers above:

对于那些已经在浏览器中使用 ES2015 的人,这里有一个使用上面的一些答案的实现:

class InputCharacterCount {
  constructor(element, min, max) {
    this.element = element;
    this.min = min;
    this.max = max;
    this.appendCharacterCount();
  }

  appendCharacterCount(){
    let charCount = `<small class="char-counter help-block"></small>`;
    this.element.closest('.form-group').append(charCount);
  }

  count(event){
    this.element.attr('maxlength', this.max); // Add maxlenght attr to input element

    let value = this.element.val();
    this.element
      .closest('.form-group')
      .find('.char-counter')
      .html(value.length+'/'+this.max); // Add a character count on keyup/keypress

    if (value.length < this.min || value.length > this.max) { // color text on min/max changes
      this.element.addClass('text-danger');
    } else {
      this.element.removeClass('text-danger');
    }
  }
}

Usage:

用法:

let comment = $('[name="collection-state-comment"]');
let counter = new InputCharacterCount(comment, 21, 140);
$(comment).keyup(function(event){
  counter.count(event);
});

回答by ProllyGeek

You can keep your event as they are , and just use this library

您可以按原样保留您的活动,只需使用此

Examples

例子

// applying a click event to one element

Touche(document.querySelector('#myButton')).on('click', handleClick);

// or to multiple at once

Touche(document.querySelectorAll('.myButtons')).on('click', handleClicks);

// or with jQuery

$('.myButtons').on('click', handleClicks);

回答by Shanish Singh

 <script type="text/javascript">
        $(document).ready(function () {
            maxlength("TextArea1");
        });
        function maxlength(id) {
            $('#' + id).on('input propertychange', function () {
                CharLimit(this, 20);
            });
        }

        function CharLimit(input, maxChar) {
            var len = $(input).val().length;
            if (len > maxChar) {
                $(input).val($(input).val().substring(0, maxChar));
            }
        }
 </script>