views:

542

answers:

2

We are trying to prevent users from typing beyond the maximum characters our DB allows for text area fields in our web app. Once they have reached the max length allowed in the text area we would still like to allow them to hit keys that are non-printing for example: Tab, backspace, ctrl+s, etc.

I'm wondering if there is a simple way to detect if a keycode is a printable character. I thought something like String.fromCharCode might do the trick and return false if it couldn't do the conversion, but doesn't seem to behave that way.

A: 

You could just set length of the textbox to the max number of characters allowed by the database

W3Schools

Cato Johnston
It would be nice if textarea tags had such a property, but that only applies to input fields, which textarea is not. Sorry I shoulda clarified that in my question.
Ben5e
+1  A: 

Try this: http://www.quirksmode.org/dom/maxlength.html

Quirksmode goes through an easy way to implement the maxlength attribute on textareas, which isn't natively supported.

And to directly answer your question:

var character = String.fromCharCode(e.charCode);

Where e is the event object of the keypress event.

Luca Matteis