title: javascript - maxLength in IE8
body: <p>Using a javascript function to prevent exceeding the length of a textfield, but to still allow pasting &amp; editing within it.  Needs to work in IE8 &amp; Firefox.  </p>
  
  <pre><code>$(function() {
      var helper = document.createElement('textarea');
      //if (!('maxLength' in helper)) {
          var supportsInput = 'oninput' in helper,
              ev = supportsInput ? 'input' : 'propertychange paste keyup',
              handler = function() {
                  var maxlength = +$(this).attr('maxlength');
                  if (this.value.length &gt; maxlength) {
                      this.value = this.value.substring(0, maxlength);
                  }
              };
  
          $('textarea[maxlength]').on(ev, supportsInput ? handler : function() {
              var that = this;
              setTimeout(function() {
                  handler.call(that);
              }, 0);
          });
      //}
  
  });
  </code></pre>
  
  <p>It works okay if the text is on one line (testing with maxLength = 25).  However, it doesn't do carriage returns &amp; line feeds or account for them properly.</p>
  
  <p>For example, if I enter the following text on one line:</p>
  
  <pre><code>1111122222333334444455555
  </code></pre>
  
  <p>it uses all 25 characters.</p>
  
  <p>However, if I enter text on each line &amp; hit enter, this is what I am able to enter:</p>
  
  <pre><code>11111
  22222
  33333
  4444
  </code></pre>
  
  <p>Which is only 22 characters.  I know that it is detecting a carriage return, because when I put in:
  11111</p>
  
  <p>a character counter shows 5.  When I hit the <code>enter</code> key, the counter goes to 6, if I enter <code>22222</code> the counter is now 11.</p>
  
  <p>The code I'm using to count the characters is:</p>
  
  <pre><code>$("#myTextArea").keyup(function() {
          var j = $(this).val().length;
          var i = 25 - j;
          $("#charsUsed").text( j );
          $("#charsLeft").text( i );
          });
  </code></pre>
  
  <p>I thought the issue might be some code I put in to resize the TextArea automatically, but it isn't.  I'm sure I am just missing something on the code &amp; would appreciate input on what I'm doing wrong &amp; haven't seem to have figured out yet.   </p>