首页 > 解决方案 > Word count display text if count is over/under 500words

问题描述

I am trying to count the number of words entered in textarea field. I would like to display the text "your text is below 500 words please write some more" if the word count is below 500words and if the count above 500 words it should say "Great job! Your text is over 500 words". How can I achieve this?

$(document).ready(function()
{
    var wordCounts = {};
    $("#my_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_word_count').html(finalCount);
        am_cal(finalCount);
    }).keyup();
 }); 
<textarea name="txtScript" id="my_word_count" cols="100" rows="10"></textarea>
<br>Total word Count : <span id="display_word_count">0</span> words.

Code Snippet

标签: jquerydomtextareaword-count

解决方案


Rather than counting word boundaries, I would suggest counting the actual words.

$(document).ready(function() {
  var $wordCountDisplay = $('#display_word_count');
  var $wordCountDisplayMessage = $('#display_word_count_message');
  var desiredMinimumWordCount = 10;
  
  $('#my_word_count').on('input', function (e) {
    var wordCount = ( e.target.value.match(/\w+/g) || [] ).length;
    $wordCountDisplay.text(wordCount);
    
    if (wordCount < desiredMinimumWordCount) {
      $wordCountDisplayMessage.text('Your text is below '+ desiredMinimumWordCount +' words please write some more');
      $wordCountDisplayMessage.removeClass('greatJob');
    } else {
      $wordCountDisplayMessage.text('Great job! Your text is over '+ desiredMinimumWordCount +' words');
      $wordCountDisplayMessage.addClass('greatJob');
    }
  }).trigger('input');
});
.greatJob { color: blue; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="txtScript" id="my_word_count" cols="100" rows="10"></textarea>
<br>Total word Count : <span id="display_word_count">0</span> words.
<br><span id="display_word_count_message"></span>


推荐阅读