javascript 使用Javascript限制Words中textarea的长度?

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

Limit length of textarea in Words using Javascript?

javascriptjquerytextarea

提问by Steven

I have the following bind on keyup which alerts if they go over 150 characters, but you can just press okay and keep typing and then just keep pressing okay.

我在 keyup 上有以下绑定,如果它们超过 150 个字符,它会发出警报,但是您可以按“确定”并继续输入,然后继续按“确定”。

I want to crop them at 150 words (not characters) and if they type over it, remove the extras. But I can't seem to figure out how to do it, I can figure out characters. But not words.

我想将它们裁剪为 150 个单词(不是字符),如果他们输入,删除多余的部分。但我似乎无法弄清楚如何去做,我可以弄清楚字符。但不是言语。

jQuery('textarea').keyup(function() {
      var $this, wordcount;
      $this = $(this);
      wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
      if (wordcount > 150) {
        jQuery(".word_count span").text("150");
        return alert("You've reached the maximum allowed words.");
      } else {
        return jQuery(".word_count span").text(wordcount);
      }
    });

采纳答案by prashanth

If you want to prevent the typing itself (when count > 150) you can do as following:

如果您想阻止打字本身(当计数 > 150 时),您可以执行以下操作:

  • Use keypress instead of keyup
  • Instead of return alert()first do an alert()and then return false;
  • 使用 keypress 而不是 keyup
  • 而不是return alert()先做一个alert()然后return false;

You may also want to add change (or blur) event handler to handle text pasting.

您可能还想添加更改(或模糊)事件处理程序来处理文本粘贴。

var maxWords = 150;
jQuery('textarea').keypress(function() {
    var $this, wordcount;
    $this = $(this);
    wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
    if (wordcount > maxWords) {
        jQuery(".word_count span").text("" + maxWords);
        alert("You've reached the maximum allowed words.");
        return false;
    } else {
        return jQuery(".word_count span").text(wordcount);
    }
});

jQuery('textarea').change(function() {
    var words = $(this).val().split(/\b[\s,\.-:;]*/);
    if (words.length > maxWords) {
        words.splice(maxWords);
        $(this).val(words.join(""));
        alert("You've reached the maximum allowed words. Extra words removed.");
    }
});?

Fiddle here

在这里摆弄

回答by Shahrokhian

/**
 * jQuery.textareaCounter
 * Version 1.0
 * Copyright (c) 2011 c.bavota - http://bavotasan.com
 * Dual licensed under MIT and GPL.
 * Date: 10/20/2011
**/
(function($){
    $.fn.textareaCounter = function(options) {
        // setting the defaults
        // $("textarea").textareaCounter({ limit: 100 });
        var defaults = {
            limit: 100
        };  
        var options = $.extend(defaults, options);

        // and the plugin begins
        return this.each(function() {
            var obj, text, wordcount, limited;

            obj = $(this);
            obj.after('<span style="font-size: 11px; clear: both; margin-top: 3px; display: block;" id="counter-text">Max. '+options.limit+' words</span>');

            obj.keyup(function() {
                text = obj.val();
                if(text === "") {
                    wordcount = 0;
                } else {
                    wordcount = $.trim(text).split(" ").length;
                }
                if(wordcount > options.limit) {
                    $("#counter-text").html('<span style="color: #DD0000;">0 words left</span>');
                    limited = $.trim(text).split(" ", options.limit);
                    limited = limited.join(" ");
                    $(this).val(limited);
                } else {
                    $("#counter-text").html((options.limit - wordcount)+' words left');
                } 
            });
        });
    };
})(jQuery);

Load that up and then you can use the following to make it work:

加载它,然后您可以使用以下内容使其工作:

$("textarea").textareaCounter({ limit: 100 });

http://bavotasan.com/2011/simple-textarea-word-counter-jquery-plugin/

http://bavotasan.com/2011/simple-textarea-word-counter-jquery-plugin/

回答by gmo

Check jQuery: Count words in real timeand this example: http://jsfiddle.net/gilly3/YJVPZ/1/

检查jQuery:实时计算单词和这个例子:http: //jsfiddle.net/gilly3/YJVPZ/1/

Then, if you want to cut the extra words... you could do something like:

然后,如果您想删除多余的单词……您可以执行以下操作:

var maxWords = 10;
if(finalCount > maxWords){
    $("#a").val(a.value.slice(0,-2)); // the -2 is to remove the extra space at the end
};

Here is a working example http://jsfiddle.net/YJVPZ/80/

这是一个工作示例http://jsfiddle.net/YJVPZ/80/

Hope it helps, Good Luck!

希望能帮到你,祝你好运!

回答by webCoder

Try this function. The valueargument should be your textarea value.

试试这个功能。该value参数应该是你的textarea的价值。

jQuery('textarea').val();


function wordcount(value)
{
    value = value.replace(/\s+/g," ");
    var andchr = value.split(" & ").length - 1;
    var char_count = value.length;
    var fullStr = value + " ";                      

    //word count for regional language
    v = value.split(' ');
    var word_count1 = v.length;                         
    var cheArr = Array('@','.','"',"'",'_','-','+','=',';','&','*','\(','\)','{','}','[','}','|','\','\,','/');                            
    for(i=0; i<=cheArr.length; i++)
    {
        word_count1 = word_count1 + value.split(cheArr[i]).length - 1;
    } 

    //word count for all languages
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");                     
    var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;

    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");                      
    var splitString = cleanedStr.split(" ");                        
    var word_count = (splitString.length - 1) + andchr;                          
    if(word_count1 > word_count)
    {
        word_count = word_count1;
    }                       
    if(value == '' || value == null || typeof(value) == 'undefined'){
        word_count = 0;
    }

    alert(word_count);

}

回答by kannanrbk

$("textarea").keyup(function(){
         var obj = $(this);
         var maxLen = 150;
         var val = obj.val();
         var chars = val.length;
         if(chars > maxLen){
              obj.val(val.substring(0,maxLen));
         }
});

回答by Stefan P.

Register to these events:

注册这些活动:

$('textarea').on('paste cut keydown', function(){...});