Javascript jquery 文本区域长度计数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4506959/
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
jquery text area length count?
提问by nimi
I have a text area field where i need to provide information about the word count when the user enters some text in the field. Length of the field is supposed to be 500 Characters.
Initialy it must show
我有一个文本区域字段,当用户在该字段中输入一些文本时,我需要在其中提供有关字数的信息。字段的长度应该是 500 个字符。最初它必须显示
min characters:100 | 0 of 500 // 0 of 500 must be in red color
最少字符数:100 | 0 of 500 // 0 of 500 必须是红色
and once the user enters come character need to update the count as well. Once the user reaches the count say the min character 100, i need to display
并且一旦用户输入来字符也需要更新计数。一旦用户达到计数说最小字符 100,我需要显示
min characters:100 | 100 of 500 // 100 of 500 must be in green color.
最少字符数:100 | 100 of 500 // 500 中的 100 必须是绿色。
How can i do this?? is there any plugin for the same??? let me know your thoughts on this.
我怎样才能做到这一点??有没有一样的插件???让我知道你对此的看法。
采纳答案by Mohan Ram
回答by gmoz22
Simplest way to count:
最简单的计算方法:
var count = $("#your_textarea").val().length;
回答by Cole
$("#your-text-area").on('keyup', function(event) {
var currentString = $("#your-text-area").val()
$("Your Div").html(currentString.length);
if (currentString.length <= 500 ) { /*or whatever your number is*/
//do some css with your div
} else {
//do some different stuff with your div
}
});
回答by syncopated
I was having trouble with the onkeydown event and had success with onkeyup. Here's the code I came up with to count down the remaining characters (with a limit of 120)
我在 onkeydown 事件上遇到了麻烦,但在 onkeyup 上取得了成功。这是我想出的对剩余字符进行倒计时的代码(限制为 120)
$(function() {
var input = $('#my-input'), display = $('.char-count'), count = 0, limit = 120;
count = input.val().length
remaining = limit - count
update(remaining);
input.keyup(function(e) {
count = $(this).val().length;
remaining = limit - count;
update(remaining);
});
function update(count) {
var txt = ( Math.abs(count) === 1 ) ? count + ' Character Remaining' : count + ' Characters Remaining'
display.html(txt);
}
});
回答by Haim Evgi
i use
我用
jQuery Textarea Characters Counter Plugin
jQuery Textarea 字符计数器插件
Examples and documentation at: http://roy-jin.appspot.com/jsp/textareaCounter.jsp