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.
我们正在尝试阻止用户输入超出我们的数据库允许在我们的网络应用程序中的文本区域字段的最大字符。一旦它们达到文本区域允许的最大长度,我们仍然希望允许它们按下非打印的键,例如:Tab,退格键,ctrl + s等。
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.
我想知道是否有一种简单的方法来检测键码是否是可打印的字符。我认为像String.fromCharCode这样的东西可以做到这一点并且如果它不能进行转换则返回false,但似乎没有这样做。
2 个解决方案
#1
Try this: http://www.quirksmode.org/dom/maxlength.html
试试这个: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.
Quirksmode通过一种简单的方法在textareas上实现maxlength属性,这种属性本身不受支持。
And to directly answer your question:
并直接回答你的问题:
var character = String.fromCharCode(e.charCode);
Where e
is the event object of the keypress
event.
其中e是keypress事件的事件对象。
#2
You could just set length of the textbox to the max number of characters allowed by the database
您只需将文本框的长度设置为数据库允许的最大字符数即可
#1
Try this: http://www.quirksmode.org/dom/maxlength.html
试试这个: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.
Quirksmode通过一种简单的方法在textareas上实现maxlength属性,这种属性本身不受支持。
And to directly answer your question:
并直接回答你的问题:
var character = String.fromCharCode(e.charCode);
Where e
is the event object of the keypress
event.
其中e是keypress事件的事件对象。
#2
You could just set length of the textbox to the max number of characters allowed by the database
您只需将文本框的长度设置为数据库允许的最大字符数即可