0

The following code works great for locking the keyboard in IE6 and IE8 when a textarea reaches a certain length. Of course, it doesn't work on other browsers, and I can't figure out a way to turn it into a jQuery function that will work cross-browser. Is it possible to get the same behavior in FireFox and Webkit browsers?

function checkLength(fld, maxLength){
    if(fld.value.length > maxLength-1){
        event.returnValue = false;
    }
}

<p><textarea name="third" id="third" onkeypress="checkLength(this, 10);">hello</textarea></p>
Eric the Red
  • 5,364
  • 11
  • 49
  • 63

2 Answers2

4

I'm going to plug my own blog here -

http://blog.jbstrickler.com/2010/11/textarea-size-limit-w-counter/

If you want something very simple, you could do -

<textarea onkeypress="return (this.value.length < 50);"></textarea>

Where 50 is how many characters you want to limit.

EDIT: Per Jason's comment, I didn't want to give the wrong impression here that inline scripting is okay...

$('textarea').keypress(function() {
  return $(this).val().length < 50;
});
John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • while this may work, this is far from ideal. inline scripting is the devil when you're trying to maintain your application later. put this into a function in a js file. – Jason Apr 26 '11 at 18:34
  • This doesn't work. If I press a key when the cursor is in the middle of my text, it deletes a character off the end. – Eric the Red Apr 26 '11 at 18:38
  • @Eric Not exactly. There is no substring'ing going on here so it won't do that. It does what your question asks, it literally locks the field from key entering when you reach your limit. Be aware it doesn't cover things such as pasting into the textarea. For that, I recommend a jQuery plugin that covers all the bases. – John Strickler Apr 26 '11 at 18:43
2

Here's a link to somebody who has done just that, with both jQuery and plain Javascript versions: http://www.ajaxray.com/blog/2007/11/09/interactive-character-limit-for-textarea-using-jquery/

Hope that helps!

Ender
  • 14,995
  • 8
  • 36
  • 51