【发布时间】:2015-06-17 10:07:30
【问题描述】:
在我的表单中,我有几个数字输入字段。通常只允许一位数字。输入一个数字后,onKeyUp 将选择下一个输入字段。但是,对于需要多个数字的情况,我想使用 '*' 作为指标。所以当用户输入 *23 时它不会跳过。
我已经走了这么远,但是当我得到输入字段的值时,我收到一个空字符串。
我想从输入中删除星号。当我尝试更改 keydown 事件中的字段输入时,其中 multi 设置为 true,输入字段值不会更改。
更改输入类型确实解决了值为"" 的问题,但随后该步骤不再起作用。
我觉得我正在为我认为应该相当简单的事情编写一大堆代码。
<input type="number" step="1" min="0" value="0">
var multi = 0;
// Keys to be ignored by the keyup event of .singleDigit.
var ignoreKeys = [ [8,46], [65,93], [107,222] ];
// Don't accept tab button, will skip an extra input field.
// Don't skip to next input, if input starts with *
// DOn't accept function buttons
$(".singleDigit").on('keyup', function(e){
if(multi == 0
&& $.isNumeric($(this).val())
&& (e.which < ignoreKeys[0][0] || e.which > ignoreKeys[0][1])
&& (e.which < ignoreKeys[1][0] || e.which > ignoreKeys[1][1])
&& e.which < ignoreKeys[2][0]) {
var inputs = $(this).closest('form').find('.input');
inputs.eq( inputs.index(this) + 1).focus();
}
});
// on focus out reset multi boolean.
$(".singleDigit").on('focusout', function() {
multi = 0;
});
// check for key combination of *
var lastKey = null;
$(".singleDigit").on('keydown', function(e){
if(lastKey != null) {
if(lastKey == 16 && e.which == 56) {
multi = 1;
}
}
if(e.which != null) {
lastKey = e.which;
}
});
【问题讨论】:
-
你为什么不使用输入类型文本并额外检查数字?
-
输入具有仅适用于数字类型的步进功能。 + 和 - 按钮是必需的。尽管只写这个而不是一团糟似乎越来越值得。
-
是的,我建议你这样做。有一个额外的功能来检查号码,你可以避免所有的混乱。
标签: javascript jquery html