jQuery 计算和限制文本区域中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17909646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting and limiting words in a textarea
提问by ashis
I managed to make this little jquery function to count the number of words entered in textarea field.
我设法使这个小 jquery 函数来计算在 textarea 字段中输入的单词数。
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
这是 html 代码
<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
总字数:0 字。剩余字数: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.
当它达到 200 个单词时,它不允许在 jquery 中的 textarea 字段中粘贴或键入更多单词?即它应限制用户输入不超过 200 个单词。
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.
编辑:仅在此代码中需要修改,因为我非常了解插件,但它们可能会干扰主代码。
回答by Michal
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, afterthe default action of that key has been performed.
使用return false
to stop keyup
events 不会阻止事件,因为在这种情况下,事件已经触发。在执行该键的默认操作后,keyup
当用户释放某个键时会触发该事件。
You will need to programmatically edit the value of the textarea
you have as #wordcount
:
您需要以编程方式编辑textarea
您拥有的值#wordcount
:
$(document).ready(function() {
$("#word_count").on('keyup', function() {
var 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);
}
});
});
回答by adeneo
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();
}
});
回答by Sparko
回答by Praveen
Adding a simple if condition
will solve your problem.
添加一个简单的if condition
将解决您的问题。
$.each(wordCounts, function(k, v) {
if(finalCount <= 200) {
//Todos
}
else {
return false; //prevent keyup event
}
});
回答by Maulik Padamani
$(document).ready(function(){ $("textarea").on('keyup',function(){
$(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");
}
});
});
});
回答by Steve Bradshaw
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>