Limit max characters using javascript
-
Add the following function to the <HEAD> section of your page:
<script language="javascript"> function LimitChars(element, maxChars){ if ( document.all(element).type == "textarea" ) { if (document.all(element).innerText.length > maxChars ) { document.all(element).innerText = document.all(element).innerText.substring(0,maxChars); } } else if ( document.all(element).type = "text") { if (document.all(element).value.length > maxChars ) { document.all(element).value = document.all(element).value.substring(0,maxChars); } } else { // nothing } } </script>
-
Ensure that any controls that this will be used for have their ID attribute set.
-
Add the following code to each control that you wish to limit the number of characters for:
onKeyUp="javascript: LimitChars(this.id, X)"
Where X is the number of characters to limit to.
Example
A <textarea> element with a limit of 10 charactersAn <input type="text"> element with a limit of 5 characters