Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
      }
    });
like image 725
Steven Avatar asked Oct 01 '12 15:10

Steven


1 Answers

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

like image 107
Shahrokhian Avatar answered Oct 16 '22 12:10

Shahrokhian