最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Limit length of textarea in Words using Javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

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);
      }
    });

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.

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.

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);
      }
    });
Share Improve this question edited Oct 1, 2012 at 15:42 Steven asked Oct 1, 2012 at 15:37 StevenSteven 14k34 gold badges102 silver badges155 bronze badges 7
  • Do not rely on keyup/down alone. Also consider the case of the user doing a right-click -> paste or text drag and drop etc. Google for "jQuery textchanged event" and you will find whats needed. – techfoobar Commented Oct 1, 2012 at 15:42
  • 2 So what should I rely on? Right click paste triggers a key up... and I have no idea what text drag drop is. – Steven Commented Oct 1, 2012 at 15:44
  • Correction, testing on Windows IE cut/paste didn't trigger key up. I'll change it to zurb.com/playground/jquery-text-change-custom-event – Steven Commented Oct 1, 2012 at 15:47
  • 1 If I were to reach the limit you impose I_would_just_start_not_using_spaces_And_I_will_get_my_say_in_no_propblem – Elias Van Ootegem Commented Oct 1, 2012 at 15:49
  • Elias, yah I know there are problems with it which is why I am not relying 100% on javascript, there is server side too. But I still want to crop it at X words and it has to be possible with javascript. – Steven Commented Oct 1, 2012 at 15:50
 |  Show 2 more comments

6 Answers 6

Reset to default 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);

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/

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

  • Use keypress instead of keyup
  • Instead of return alert() first do an alert() and then 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

Check jQuery: Count words in real time and this example: 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/

Hope it helps, Good Luck!

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

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);

}
$("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));
         }
});

Register to these events:

$('textarea').on('paste cut keydown', function(){...});
发布评论

评论列表(0)

  1. 暂无评论