Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - 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(//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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...