Javascript 计算 textarea 字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14086398/
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
Count textarea characters
提问by Ilan Biala
I am developing a character count for my textarea on this website. Right now, it says NaN because it seems to not find the length of how many characters are in the field, which at the beginning is 0, so the number should be 500. In the console in chrome developer tools, no error occur. All of my code is on the site, I even tried to use jQuery an regular JavaScript for the character count for the textarea field, but nothing seems to work.
我正在为这个网站上的 textarea 开发一个字符数。现在说NaN是因为好像没查到字段有多少个字符的长度,开头是0,所以数字应该是500。在chrome开发者工具的控制台,没有报错。我的所有代码都在网站上,我什至尝试使用 jQuery 和常规 JavaScript 来计算 textarea 字段的字符数,但似乎没有任何效果。
Please tell me what I am doing wrong in both the jQuery and the JavaScript code I have in my contact.js file.
请告诉我在我的 contact.js 文件中的 jQuery 和 JavaScript 代码中我做错了什么。
$(document).ready(function() {
var tel1 = document.forms["form"].elements.tel1;
var tel2 = document.forms["form"].elements.tel2;
var textarea = document.forms["form"].elements.textarea;
var clock = document.getElementById("clock");
var count = document.getElementById("count");
tel1.addEventListener("keyup", function (e){
checkTel(tel1.value, tel2);
});
tel2.addEventListener("keyup", function (e){
checkTel(tel2.value, tel3);
});
/*$("#textarea").keyup(function(){
var length = textarea.length;
console.log(length);
var charactersLeft = 500 - length;
console.log(charactersLeft);
count.innerHTML = "Characters left: " + charactersLeft;
console.log("Characters left: " + charactersLeft);
});a?*/
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
});
function checkTel(input, nextField) {
if (input.length == 3) {
nextField.focus();
} else if (input.length > 0) {
clock.style.display = "block";
}
}
function textareaLengthCheck(textarea) {
var length = textarea.length;
var charactersLeft = 500 - length;
count.innerHTML = "Characters left: " + charactersLeft;
}
回答by Andrew Hubbs
$("#textarea").keyup(function(){
$("#count").text($(this).val().length);
});
The above will do what you want. If you want to do a count down then change it to this:
以上将做你想做的。如果要倒计时,请将其更改为:
$("#textarea").keyup(function(){
$("#count").text("Characters left: " + (500 - $(this).val().length));
});
Alternatively, you can accomplish the same thing without jQueryusing the following code. (Thanks @Niet)
或者,您可以在不jQuery使用以下代码的情况下完成相同的操作。(感谢@Niet)
document.getElementById('textarea').onkeyup = function () {
document.getElementById('count').innerHTML = "Characters left: " + (500 - this.value.length);
};
回答by Etienne Martin
?? The accepted solution is outdated.
?? 已接受的解决方案已过时。
Here are two scenarios where the keyupevent will not get fired:
以下是keyup不会触发事件的两种情况:
- The user drags text into the textarea.
- The user copy-paste text in the textarea with a right click (contextual menu).
- 用户将文本拖入文本区域。
- 用户通过右键单击(上下文菜单)在 textarea 中复制粘贴文本。
Use the HTML5 inputevent instead for a more robust solution:
改用 HTML5input事件以获得更强大的解决方案:
<textarea maxlength='140'></textarea>
JavaScript (demo):
JavaScript(演示):
const textarea = document.querySelector("textarea");
textarea.addEventListener("input", event => {
const target = event.currentTarget;
const maxLength = target.getAttribute("maxlength");
const currentLength = target.value.length;
if (currentLength >= maxLength) {
return console.log("You have reached the maximum number of characters.");
}
console.log(`${maxLength - currentLength} chars left`);
});
And if you absolutely want to use jQuery:
如果你绝对想使用 jQuery:
$('textarea').on("input", function(){
var maxlength = $(this).attr("maxlength");
var currentLength = $(this).val().length;
if( currentLength >= maxlength ){
console.log("You have reached the maximum number of characters.");
}else{
console.log(maxlength - currentLength + " chars left");
}
});
回答by Niet the Dark Absol
textarea.addEventListener("keypress", textareaLengthCheck(textarea), false);
You are callingtextareaLengthCheckand then assigning its return value to the event listener. This is why it doesn't update or do anything after loading. Try this:
您正在调用textareaLengthCheck,然后将其返回值分配给事件侦听器。这就是为什么它在加载后不更新或做任何事情的原因。尝试这个:
textarea.addEventListener("keypress",textareaLengthCheck,false);
Aside from that:
除此之外:
var length = textarea.length;
textareais the actual textarea, not the value. Try this instead:
textarea是实际的文本区域,而不是值。试试这个:
var length = textarea.value.length;
Combined with the previous suggestion, your function should be:
结合前面的建议,你的函数应该是:
function textareaLengthCheck() {
var length = this.value.length;
// rest of code
};
回答by Shafiqul Islam
Here is simple code. Hope it is working
这是简单的代码。希望它有效
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters remaining');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="textarea" rows="8" cols="30" maxlength="99" ></textarea>
<div id="textarea_feedback"></div>
回答by Kurenai Kunai
This code gets the maximum value from the maxlengthattribute of the textareaand decreases the value as the user types.
此代码从 的maxlength属性中获取最大值,textarea并随着用户键入而减小该值。
<DEMO>
<演示>
var el_t = document.getElementById('textarea');
var length = el_t.getAttribute("maxlength");
var el_c = document.getElementById('count');
el_c.innerHTML = length;
el_t.onkeyup = function () {
document.getElementById('count').innerHTML = (length - this.value.length);
};
<textarea id="textarea" name="text"
maxlength="500"></textarea>
<span id="count"></span>
回答by Martin Joergensen
For those wanting a simple solution without jQuery, here's a way.
对于那些想要一个没有 jQuery 的简单解决方案的人,这里有一个方法。
textarea and message container to put in your form:
要放入表单的 textarea 和消息容器:
<textarea onKeyUp="count_it()" id="text" name="text"></textarea>
Length <span id="counter"></span>
JavaScript:
JavaScript:
<script>
function count_it() {
document.getElementById('counter').innerHTML = document.getElementById('text').value.length;
}
count_it();
</script>
The script counts the characters initially and then for every keystroke and puts the number in the counter span.
该脚本最初对字符进行计数,然后对每次击键进行计数,并将该数字放入计数器范围内。
Martin
马丁
回答by Nielsvh
I found that the accepted answer didn't exactly work with textareas for reasons noted in Chrome counts characters wrong in textarea with maxlength attributebecause of newline and carriage return characters, which is important if you need to know how much space would be taken up when storing the information in a database. Also, the use of keyup is depreciated because of drag-and-drop and pasting text from the clipboard, which is why I used the inputand propertychangeevents. The following takes newline characters into account and accurately calculates the length of a textarea.
我发现接受的答案并不完全适用于textareas,原因在Chrome 中指出的原因,由于换行符和回车符,在具有 maxlength 属性的 textarea 中计数错误的字符,如果您需要知道将占用多少空间,这一点很重要将信息存储在数据库中。此外,由于从剪贴板拖放和粘贴文本,keyup 的使用会贬值,这就是我使用inputandpropertychange事件的原因。下面将换行符考虑在内并准确计算 a 的长度textarea。
$(function() {
$("#myTextArea").on("input propertychange", function(event) {
var curlen = $(this).val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length;
$("#counter").html(curlen);
});
});
$("#counter").text($("#myTextArea").val().replace(/\r(?!\n)|\n(?!\r)/g, "\r\n").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="myTextArea"></textarea><br>
Size: <span id="counter" />
回答by PK-1825
$(document).ready(function(){
$('#characterLeft').text('140 characters left');
$('#message').keydown(function () {
var max = 140;
var len = $(this).val().length;
if (len >= max) {
$('#characterLeft').text('You have reached the limit');
$('#characterLeft').addClass('red');
$('#btnSubmit').addClass('disabled');
}
else {
var ch = max - len;
$('#characterLeft').text(ch + ' characters left');
$('#btnSubmit').removeClass('disabled');
$('#characterLeft').removeClass('red');
}
});
});
回答by Ronnie Royston
They say IE has issues with the inputevent but other than that, the solution is rather straightforward.
他们说 IE 有input事件问题,但除此之外,解决方案相当简单。
ta = document.querySelector("textarea");
count = document.querySelector("label");
ta.addEventListener("input", function (e) {
count.innerHTML = this.value.length;
});
<textarea id="my-textarea" rows="4" cols="50" maxlength="10">
</textarea>
<label for="my-textarea"></label>
回答by Junior
This solution will respond to keyboard and mouse events, and apply to initial text.
此解决方案将响应键盘和鼠标事件,并适用于初始文本。
$(document).ready(function () {
$('textarea').bind('input propertychange', function () {
atualizaTextoContador($(this));
});
$('textarea').each(function () {
atualizaTextoContador($(this));
});
});
function atualizaTextoContador(textarea) {
var spanContador = textarea.next('span.contador');
var maxlength = textarea.attr('maxlength');
if (!spanContador || !maxlength)
return;
var numCaracteres = textarea.val().length;
spanContador.html(numCaracteres + ' / ' + maxlength);
}
span.contador {
display: block;
margin-top: -20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="100" rows="4">initial text</textarea>
<span class="contador"></span>

