简体   繁体   中英

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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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