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".
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.