How to impose maxlength on TextArea in HTML using JavaScript
The key to limit the textarea
input length in JavaScript is the input
event which trims the entered text as per the defined maxlength
on any text change. Here goes the basics of it:
This registers an event listener to the textarea
and trims its content to the limit whenever the user types or pastes text exceeding it.
The dive-in answer
Seamless UX with dynamic content
In a world where web content is loaded and shuffled dynamically, attaching event listeners directly seems so 90s. Instead, we wear our smart pants and use event delegation:
Handling the 'Ctrl+V' surprise
Users might just paste
a War and Peace novel into your textarea
. To prevent such textual onslaught, handle the paste
event:
The setTimeout
employed here ensures that our textarea
accommodates the pasted text before we yield the chopping blade.
Support à la old browsers
Life hasn't been kind on some elderly browsers not supporting the maxlength
on textarea
natively. We, being good Samaritans, provide them a walking stick:
This method ensures even in the absence of native HTML5 support, our maxlength
remains a rockstar.
The 'even finer' control
To have an upper hand over the keyboard inputs, roll over the keydown
event:
BFF with jQuery
If your stack includes jQuery, handling maxlength
is like a walk in the park:
With jQuery's on
method, it doesn't matter if your textareas are appearing dynamically or are statically present.
Welcome polite coders
Offer feedback and be gentle to your users:
Was this article helpful?