Enforcing Maximum Length on HTML Textareas Using JavaScript
How can you impose a maximum length on
One method involves handling keypress events using onkeypress and onkeyup attributes in each textarea:
<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50"></textarea> <script> function imposeMaxLength(event, object, maxLength) { return (object.value.length <= maxLength) || (event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 35 && event.keyCode <= 40)); } </script>
However, manually adding these attributes to every textarea can become tedious. Here's an alternative approach that automates the process:
window.onload = function() { var txts = document.getElementsByTagName('TEXTAREA'); for (var i = 0, l = txts.length; i < l; i++) { if (/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { var func = function() { var len = parseInt(this.getAttribute("maxlength"), 10); if (this.value.length > len) { alert('Maximum length exceeded: ' + len); this.value = this.value.substr(0, len); return false; } } txts[i].onkeyup = func; txts[i].onblur = func; } } };
This script initializes on page load and iterates through all
The above is the detailed content of How to Enforce Maximum Length on HTML Textareas Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!