【发布时间】:2015-09-26 07:34:13
【问题描述】:
我想向用户显示一条错误消息,如果他在文本字段中输入的字符多于指定的字符,并且此规范可能会随着提供的初始字符而改变。除此之外,我需要处理用户出于某些业务目的输入的每个字符。 例如
不同的信用卡类型有不同的最大长度。我想阻止用户在字段中输入比他们的信用卡类型允许的更多的字符。
但是,只有当用户提供的信用卡首字母很少时,才能检测到信用卡类型。
我的方法是尝试在每次按键时检测信用卡,并根据检测到的信用卡类型设置字段的最大长度。如果未检测到,则将最大长度保持为 19(这是所有的最大值)
我的尝试
---------------------------------------------------------------------
| Event | Problem |
| ------------------------------------------------------------------|
| | Change will not be triggered until the user |
| OnChange | moves out of the field. Since I need this event |
| | on every char entered, this is not helpful |
|-------------------------------------------------------------------|
| | It gives issues when a user presses the key for a |
| KeyDown | longer duration. Characters are entered multiple |
| | times, but this event is triggered only once. |
|-------------------------------------------------------------------|
| KeyUP | Same as above. |
|-------------------------------------------------------------------|
| KeyPress | I am getting older value. The newly added character |
| | is not available. Hence incorrect calculation |
---------------------------------------------------------------------
我有一个使用超时的替代方法,但正在寻找更好的选择。
由于上述原因,我的问题与this one. 不同。
请为此提出一个好的解决方案。
【问题讨论】:
-
请出示相关代码。
-
使用 .change(function(){ ... });而不是 keypress();
-
@Ji_in_coding
change仅在input元素失去焦点时触发,这听起来不像 OP 想要的行为。 -
如何使用keydown..并使用“counter”变量?
-
@MohitKanwar 你说你不能用
keyup,但是你试过keydown吗?
标签: javascript jquery