Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting and limiting words in a textarea

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.

like image 824
ashis Avatar asked Jul 28 '13 15:07

ashis


People also ask

How do I limit the number of words in a textarea?

Limit character input in the textarea including count. JavaScript Code : var maxLength = 15; $('textarea'). keyup(function() { var textlen = maxLength - $(this).


2 Answers

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/

like image 52
Michal Avatar answered Sep 17 '22 04:09

Michal


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

like image 39
adeneo Avatar answered Sep 17 '22 04:09

adeneo