jquery - 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.
解决方案
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>
推荐阅读
- python - 对二维字符串列表python进行排序
- firebase - Firebase:当他们注册 Google Provider 时,如何处理具有相同 displayNames 的用户?
- google-apps-script - 发布到 Google 表格会给出 {"result":"error","error":{"name":"Exception"}}
- excel - 如何执行 VBA 代码以仅从选择中获取某些列,然后粘贴到另一张表的末尾
- etl - 如何在 apache nifi 中使用 putSQL
- macos - 由 launchd 运行的脚本不评估环境变量
- reactjs - React component not re-rendering when props change
- tensorflow - 使用 Keras 训练批量数据实现自定义损失
- swiftui - 它没有读取设置已更改
- java - Spring Boot + Java 模块 = 不支持的类文件主要版本