Limiting TextArea Characters In Internet Explorer

In my last project I ran into an annoying nuance of IE9 but turned out to be IE (Internet Explorer) in general.  IE does not like to acknowledge the maxLength property that you can set on a <textarea> tag.  In FireFox as well as in Chrome you could set this property to the desired length and the browser would acknowledge this and stop user input at the desired length.  Take a look at the following snippet.

<textarea id="limitChars" rows="5" cols="86" maxlength="1000">

In this snippet, the attribute to look at is maxlength=”1000″.  Make sure you have this set as it works well in FireFox and in Chrome.  Now, let’s talk about Internet Explorer.  From my project it looks like IE7, IE8, IE9, and IE10 don’t care about the maxlength attribute and will let the user keep typing long beyond what you desire.  So there are two pieces to this puzzle that I found fit my likings best.  The first is we bind the <textarea> to the keyup event like so.

$('# limitChars').keyup(function () {
     //Code
});

In binding the textarea to this keyup event it will be fired on every keystroke.  So inside of this event we now just have to check the length of characters in the texarea and either do nothing or we will cut it down.  So let’s add the code in the middle.

$('#limitChars').keyup(function () {
     //Get the value of the textarea.
     var valueOfInput = $("#limitChars").val();

     //Check and see if its over our desired limit.

     if (valueOfInput.length > 1000) {
          //We reset the characters they have typed and cut it off to 1000.

          $("#limitChars").html(valueOfInput.substr(0, 1000));
     }
});

It causes a bit of weird behavior when they get to the limit but up until that limit it works quite well.


Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile