8

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

我想将它们裁剪为 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);
      }
    });
4

6 回答 6

9
/**
 * 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);

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

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

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

于 2012-10-01T16:09:36.480 回答
5

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

  • 使用 keypress 而不是 keyup
  • 而不是return alert()先做一个alert()然后return false;

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

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.");
    }
});​

在这里提琴

于 2012-10-01T16:19:00.140 回答
1

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

然后,如果你想减少多余的单词......你可以这样做:

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

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

希望对您有所帮助,祝您好运!

于 2012-10-01T16:11:25.107 回答
0
$("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));
         }
});
于 2012-10-01T16:04:43.310 回答
0

试试这个功能。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);

}
于 2012-10-01T15:51:02.067 回答
-1

注册这些事件:

$('textarea').on('paste cut keydown', function(){...});
于 2012-10-01T15:49:44.033 回答