简体   繁体   English

如何从输入类型编号中读取特殊字符

[英]How to read special characters from input type number

In my form I have a few number input fields. 在我的表单中,我有一些数字输入字段。 Normally there is only one digit allowed. 通常,只允许一位数字。 After that one digit has been put in, onKeyUp the next input field is selected. 输入一位数字后,在onKeyUp上选择下一个输入字段。 However for the cases where more than one digit are required I want to use '*' as an indicator. 但是对于需要多一位数字的情况,我想使用'*'作为指标。 So when the users types *23 it won't skip. 因此,当用户键入* 23时,它不会跳过。

I have come that far, however when I get the value of the input field I receive an empty string. 我走了这么远,但是当我得到输入字段的值时,我收到一个空字符串。

I want to remove the asterisk from the input. 我想从输入中删除星号。 When I try to alter the input of the field in the keydown event, where multi is set to true, the input field value is not altered. 当我尝试在keydown事件(其中multi设置为true)中更改字段的输入时,输入字段的值不会更改。

Altering the input type does fix the problem with the value being "" , but then the step isn't functional any more. 更改输入类型确实解决了值为"" ,但是该步骤不再起作用。

I feel like I'm making a giant pile of code for something I feel should be fairly simple. 我觉得我正在为一堆我认为应该很简单的代码编写大量代码。

<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;
  }
});

I found a way around it. 我找到了解决方法。 Since I have the event, I can just prevent the default action. 由于有了事件,因此可以阻止默认操作。

var lastKey = null;
$(".singleDigit").on('keydown', function(e){
  if(lastKey != null) {
    if(lastKey == 16 && e.which == 56) {
      multi = 1;
      e.preventDefault();
    } 
  }
  if(e.which != null) {
    lastKey = e.which;
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM