Question

I need some help with adding a max_word value to a jquery word counter that I found (http://roshanbh.com.np/2008/10/jquery-plugin-word-counter-textarea.html)

I've modified the above code slightly as I have multiple textareas which need to be limited, but I'm not sure how to make the textarea stop after the user has inputted say 100 words.

Here's the code:

jQuery.fn.wordCount = function(params){
  var p = {
    counterElement: "display_count"
  };
  var total_words;
  if(params) {
    jQuery.extend(p, params);
  }
  //for each keypress function on text areas
  this.keypress(function() { 
    total_words = this.value.split(/[\s\.\?]+/).length;
    jQuery(this).parent().find("."+p.counterElement).html(total_words);
  });   
};

jQuery(".word_count").wordCount();

<textarea name="question_1" id="question_1" class="word_count"></textarea><div class="counter">Total words: <span class="display_count">0</span></div>

<textarea name="question_2" id="question_2" class="word_count"></textarea><div class="counter">Total words: <span class="display_count">0</span></div>

<textarea name="question_3" id="question_3" class="word_count"></textarea><div class="counter">Total words: <span class="display_count">0</span></div>

Any help would be greatly appreciated :)

Was it helpful?

Solution

The only way to make user stop is to do this.value = this.value.substr(0,100); However, this is bad user experience that makes user hard to type.

Consider blocks user from sending the content when clicking submit instead. Twitter do that, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top