In web development, it's often necessary to control the maximum length of text entered into text areas. This scenario requires you to automatically enforce the maxlength attribute on multiple text areas. While previous solutions involved manual event handling for each text area, we'll explore an alternative approach that eliminates the need for repetitive code.
The key to this solution lies in JavaScript's ability to scan the page for all text areas and dynamically add event listeners to the appropriate ones. By leveraging the onload event, we gain access to the entire page's content upon loading, including any text areas.
window.onload = function() {
Now, we can traverse the document, searching for all elements with the TEXTAREA tag:
var txts = document.getElementsByTagName('TEXTAREA');
Next, we iterate through each text area to check if it has a valid maxlength attribute. Note that we use a regular expression to ensure that the maxlength value is a number.
for(var i = 0, l = txts.length; iFor each qualifying text area, we define a callback function to validate the maximum length. This function will:
- Retrieve the value of the maxlength attribute as an integer
- Check if the current length of the text area's value exceeds the maxlength
- If exceeded, display an alert message and truncate the value to the maximum allowed length
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; } }Finally, we attach this callback function to both the keyup and blur events of the text area.
txts[i].onkeyup = func; txts[i].onblur = func;This comprehensive approach provides a seamless solution for automatically imposing a maxlength on all qualifying text areas on a web page without the need for repetitive event handling.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3