Sometimes, we want to count and limit words in a text area with JavaScript.
In this article, we’ll look at how to count and limit words in a text area with JavaScript.
How to count and limit words in a text area with JavaScript?
To count and limit words in a text area with JavaScript, we can check the length of the text area’s value in the keypress event handler.
For instance, we write:
<textarea></textarea>
to add a text area.
Then we write:
const textarea = document.querySelector('textarea')
textarea.onkeypress = (e) => {
if (e.target.value.length > 20) {
e.preventDefault()
}
};
to select the text area with querySelector
.
Next, we set textarea.onkeypress
to a function that checks if the text area’s input value is bigger than 20.
If it is, then we call e.preventDefault
to stop appending the typed characters to the text area’s input value.
Conclusion
To count and limit words in a text area with JavaScript, we can check the length of the text area’s value in the keypress event handler.