[英]How to count characters when pressing tab, space,delete and backspace?
I know this question may be a duplicate but I wasn't able to find a solution so far. 我知道这个问题可能是重复的,但到目前为止我还找不到解决方案。 Maybe the way I searched is wrong. 也许我搜索的方式是错误的。
I need to count the total characters of textarea
along with spaces using "space key" "tab key" "delete" or "backspace". 我需要使用“空格键”,“选项卡键”,“删除”或“退格键”来计算textarea
的总字符以及空格。
So far I have the below code but I don't know why it is not considering tab space in the count. 到目前为止,我有下面的代码,但我不知道为什么它不考虑计数中的制表符空间。
<textarea id="myTextArae"></textarea>
$("#myTextArae").on("keydown", function(e) {
if (e.keyCode === 9) { // tab was pressed
let start = this.selectionStart;
let end = this.selectionEnd;
var $this = $(this);
$this.val($this.val().substring(0, start) + "\t" + $this.val().substring(end));
this.selectionStart = this.selectionEnd = start + 1;
var txt = $("#balanceCharacInTxtarea").val();
if (txt != parseInt("0")) {
e.preventDefault();
}
return false;
}
})
$("#myTextArea").on("paste", function (e) {
setTimeout(function () {
that.check(e, e1, 0);
}, 100);
});
check(eventcode, e1, code) {
if (code === 0) {
this.calculate = this.characterCount(e, e1, default);
} if (code === 1) {
this.calculate = e1 ? e1.length : 0;
}
}
var default = 175
How about something as easy as 像这样简单的事情怎么样
$("#yourtextarea").keyup(function() {
var count = $("#yourtextarea").val().length;
});
This will count spaces, tabs, newlines and other characters. 这将计算空格,制表符,换行符和其他字符。
It will trigger on paste as well. 它也会在粘贴时触发。
Example : 范例 :
$(document).ready(function(){ $("#test").html(0); //this is for counting the characters $("#message").keyup(function() { var txtlgt = $("#message").val().length; $("#test").html(txtlgt); }); //This is for enabling tabs in the textarea $("#message").on("keydown", function(e) { if (e.keyCode === 9){ let start = this.selectionStart; let end = this.selectionEnd; var $this = $(this); $this.val($this.val().substring(0, start) + "\\t" + $this.val().substring(end)); this.selectionStart = this.selectionEnd = start + 1; return false; } }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test"></div> <textarea id="message"></textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.