blog.michaelfasani.com

Blog, What?

Wednesday, August 13, 2008

Limiting a multi-line Textbox/Textarea with JavaScript

Its not possible to put a character limit on multi line text box areas in HTML/XHTML so you have to use some form of JavaScript snippet, here is a snippet I use, because its quick and very simple to customize.

<script type="text/javascript">
//Max length multiline textbox checker
function checkMaxLen(txt,maxLen) {
try{
if(txt.value.length > (maxLen-1)) {
var cont = txt.value;
txt.value = cont.substring(0,(maxLen -1));
return false;
};
}catch(e){
}
};
</script>

Then use the following code on the Textarea tag.

<textarea onkeyup="return checkMaxLen(this,5000)"></textarea>

You simply set the text limit by changing the value in the JavaScript function from 5000 to what ever number of characters you need.

posted by Michael Fasani at 7:59 pm  

3 Comments »

  1. Or you could just set ‘maxlength’ on the control in the development environment which handled this for you with no need for knowledge of javascript.

    Seriously outdated advice, not sure I agree with advice being posted which is obsolete.

    Comment by TheCoder — August 14, 2008 @ 4:19 pm

  2. Max length doesn’t work on TEXTAREA, thats the point….

    Comment by Michael Fasani — September 19, 2008 @ 10:36 am

  3. I believe you can limit the text field in textarea boxes that runs serverside on the .Net platform. Using a RegularExpression Validator will sort this out with ease (or you could use a custom validator too).

    One other thing, if you set the textmode of the field to “SingleLine” or “Password” then Maxlength magically works!

    Comment by Neil-One — September 22, 2008 @ 10:13 am

RSS feed for comments on this post. TrackBack URI

Leave a comment


Powered by WordPress