How to display dynamically the number of typed characters in textarea?
-
All greetings, there is
textarea
and its layout has a maximum length of 360 characters, how to dynamically display how many characters have been hammered into the field using native JavaScript? Screen for clarityJavaScript Evan Orr, Jul 12, 2020 -
Use the input event on the textarea and take event.target.value.length in the handler - the number of characters driven. And push it into this counter.
const ta = document.querySelector(...) // textarea
const counter = document.querySelector(...) // счётчик
ta.addEventListener('input', onInput)
funcion onInput(evt) {
const length = evt.target.value.length
counter.textContent = length
}
August Gilmore -
https://jsfiddle.net/yarkov_aleksei/a4x6p1s3/
<div class="container">
<textarea name="" id="" cols="30" rows="10"></textarea>
<div class="counter">
<span class="current">0</span> /
<span class="total">360</span>
</div>
</div>
.container {
position: relative;
width: max-content;
}
.counter {
position: absolute;
bottom: 5px;
right: 5px;
}
const textarea = document.querySelector('textarea');
const counter = document.querySelector('.current');
const maxlength = 360;
textarea.addEventListener('input', onInput)
function onInput(event) {
event.target.value = event.target.value.substr(0, maxlength); // обрезаем текст до 360 символов
const length = event.target.value.length;
counter.textContent = length;
}Anonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!