Explain Codes LogoExplain Codes Logo

How to impose maxlength on TextArea in HTML using JavaScript

html
responsive-design
event-delegation
maxlength
Nikita BarsukovbyNikita Barsukov·Nov 27, 2024
TLDR

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:

// Select the textarea const textarea = document.querySelector('textarea'); // Add an "input" event listener textarea.addEventListener('input', () => { // Stealing letters beyond limit, sneaky JavaScript! textarea.value = textarea.value.slice(0, 100); });

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:

// We are the sippers of tea here, watching events as they unfold. document.addEventListener('input', (event) => { if (event.target.tagName === 'TEXTAREA' && event.target.maxLength > 0) { // Chopping off extra letters like a ninja! event.target.value = event.target.value.slice(0, event.target.maxLength); } });

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:

textarea.addEventListener('paste', (event) => { // Let's give our pasted text a little breathing space, shall we? setTimeout(() => { // Swiping the extra letters off, swish! textarea.value = textarea.value.slice(0, textarea.maxLength); }, 0); });

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:

window.onload = function() { var textareas = document.getElementsByTagName('TEXTAREA'); for (var i = 0; i < textareas.length; i++) { if(textareas[i].getAttribute('maxlength')) { textareas[i].onkeyup = textareas[i].onblur = enforceMaxLength; } } function enforceMaxLength(event) { var target = event.target; var maxLength = parseInt(target.getAttribute('maxlength')); if (target.value.length > maxLength) { // Like good barbers, we love giving good trims. target.value = target.value.substring(0, maxLength); // Little heads-up for overly enthusiastic typers. alert('Chill mate! Maximum length exceeded!'); } } };

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:

textarea.addEventListener('keydown', (event) => { if (textarea.value.length >= textarea.maxLength && !event.metaKey && !event.ctrlKey && event.keyCode != 8 && event.keyCode != 46) { // Hey you! No Cheating! event.preventDefault(); } });

BFF with jQuery

If your stack includes jQuery, handling maxlength is like a walk in the park:

$('textarea[maxlength]').on('input', function() { // jQuery to the rescue! var maxLength = parseInt($(this).attr('maxlength')); $(this).val($(this).val().substring(0, maxLength)); });

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:

textarea.onblur = function() { if(this.value.length > this.maxLength) { // Adding a bit of color to our error this.classList.add('error'); // Politeness level: British alert('Apologies, it appears your text is a bit too long!'); } };