21

I managed to make this little jquery function to count the number of words entered in textarea field.

here is the fiddle

and here is the code:

JQUERY:

$(document).ready(function()
{
var wordCounts = {};
$("#word_count").keyup(function() {
    var matches = this.value.match(/\b/g);
    wordCounts[this.id] = matches ? matches.length / 2 : 0;
    var finalCount = 0;
    $.each(wordCounts, function(k, v) {
        finalCount += v;
    });
    $('#display_count').html(finalCount);
    am_cal(finalCount);
}).keyup();
}); 

and here is html code

<textarea name="txtScript" id="word_count" cols="1" rows="1"></textarea>
Total word Count : <span id="display_count">0</span> words.

how can i make modifications in it to have the output like this

Total word Count : 0 words. Words left : 200

and when it reach 200 words it shall not allow to either paste, or type more words in the textarea field, in jquery? i.e. it shall restrict user to type exactly 200 words not more than that.

Please help.

Thanks a lot in advance.

EDIT: The modification is needed in this code only, as i am very well aware of the plugins, but they may interfere with the main code.

Michal
  • 2,532
  • 1
  • 19
  • 27
ashis
  • 381
  • 1
  • 3
  • 16

7 Answers7

52

Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.

You will need to programmatically edit the value of the textarea you have as #wordcount:

$(document).ready(function() {
  $("#word_count").on('keyup', function() {
    var words = 0;

    if ((this.value.match(/\S+/g)) != null) {
      words = this.value.match(/\S+/g).length;
    }

    if (words > 200) {
      // Split the string on first 200 words and rejoin on spaces
      var trimmed = $(this).val().split(/\s+/, 200).join(" ");
      // Add a space at the end to make sure more typing creates new words
      $(this).val(trimmed + " ");
    }
    else {
      $('#display_count').text(words);
      $('#word_left').text(200-words);
    }
  });
});

http://jsfiddle.net/k8y50bgd/

Multihunter
  • 5,520
  • 2
  • 25
  • 38
Michal
  • 2,532
  • 1
  • 19
  • 27
  • My original answer did not take your blocking-copy-paste-when-over-200 into account. Now it truncates. You will want to do some UI work to make the user more aware of what is happening, I think. – Michal Jul 28 '13 at 16:01
  • means?? what do you want to suggest? – ashis Jul 28 '13 at 16:33
  • Yes, sorry for the confusion. I had already fixed it, I was just commenting on a past version of the answer. – Michal Jul 28 '13 at 16:49
  • was looking for a solution like this and this just did the trick. Answer is old but still holds up. +1 – Syfer Sep 13 '18 at 11:41
4

I would do it like this ?

$("#word_count").on('keydown', function(e) {
    var words = $.trim(this.value).length ? this.value.match(/\S+/g).length : 0;
    if (words <= 200) {
        $('#display_count').text(words);
        $('#word_left').text(200-words)
    }else{
        if (e.which !== 8) e.preventDefault();
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

A simple plugin can be found here:

Simple Textarea Word Counter using jQuery

Sparko
  • 735
  • 6
  • 15
  • 1
    i know of many plugins over the internet but i do not want to use them as just a slight modification in this code will do it. but i could not figure out the same.. hence i posted the question here. – ashis Jul 28 '13 at 15:14
  • If a plugin is unsuitable (or you're unable to extract the relevant code from the above example) you should specify this in your question. – Sparko Jul 28 '13 at 15:19
1

Adding a simple if condition will solve your problem.

$.each(wordCounts, function(k, v) {
    if(finalCount <= 200) {
        //Todos
    }
    else {
      return false;  //prevent keyup event
    }
 });
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • 1
    @user1671639 The `return false;` will not prevent the user's typing. It prevents the keyup event, but that event fires after the key has already been released and the key's default action has been performed. – Michal Jul 28 '13 at 17:09
0

$(document).ready(function(){ $("textarea").on('keyup',function(){

                var value = $('textarea').val();
                var wordCount = 0;

                if(value == ""){
                    $('textarea').empty();
                }
                else{

                    var regex = /\s+/gi;
                    var wordCount = value.trim().replace(regex, ' ').split(' ').length;
                }

                    if(wordCount > 25){
                     var trimmed = $(this).val().split(/\s+/,25).join(" ");
                    $(this).val(trimmed + " ");
            }
            else{
                $('#display_count').html(25- wordCount +" words left");
            }


              });

});

  • 1
    Please add more description and/or information about your answer and how it solves the asked problem so others can easily understand it without asking for clarification – koceeng Feb 25 '17 at 06:04
0

You can use positive lookahead regexes to preserve the whitespace - so that returncodes and tabs are not collapsed to a single space. Something like this:

  var wordLimit = 5;
  var words = 0;
  var jqContainer = $(".my-container");
  var jqElt = $(".my-textarea");

function charLimit()
{
  var words = 0;
  var wordmatch = jqElt.val().match(/[^\s]+\s+/g);
  words = wordmatch?wordmatch.length:0;

  if (words > wordLimit) {
      var trimmed = jqElt.val().split(/(?=[^\s]\s+)/, wordLimit).join("");
      var lastChar = jqElt.val()[trimmed.length];
      jqElt.val(trimmed + lastChar);
  }
  $('.word-count', jqContainer).text(words);
  $('.words-left', jqContainer).text(Math.max(wordLimit-words, 0));
 }
 
 jqElt.on("keyup", charLimit);
 charLimit();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="my-container">
  <textarea class="my-textarea"></textarea>
  <span class="words-left"></span> words left
<div>
Steve Bradshaw
  • 827
  • 7
  • 10
0

Here is the final solution.

(function(){
  
  $("textarea").after("<p>Number of words: <span class='count'>0</span>/10</p>");
  
  $("textarea").keypress(function(){    
    
    var words = $.trim($(this).val()).split(" ").filter(function(word){
     return $.trim(word).length > 0
    });
    
    var wordlength = words.length;
    $(".count").text(wordlength);
    
    if(wordlength > 10){           
       alert("Please do not enter more than 10 words");
       $(this).val( words.splice(0,10).join(" "));
       return false;
    }   
  })
})
Kaleem Nalband
  • 687
  • 7
  • 21