Steven
Steven

Reputation: 13975

Limit length of textarea in Words using Javascript?

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

Upvotes: 8

Views: 16483

Answers (6)

prashanth
prashanth

Reputation: 2099

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

Upvotes: 5

gmo
gmo

Reputation: 9000

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!

Upvotes: 1

Shahrokhian
Shahrokhian

Reputation: 1114

/**
 * 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/

Upvotes: 9

kannanrbk
kannanrbk

Reputation: 7134

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

Upvotes: 0

webCoder
webCoder

Reputation: 2222

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

}

Upvotes: 0

Stefan P.
Stefan P.

Reputation: 9519

Register to these events:

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

Upvotes: -1

Related Questions