I'm making a system where you press a key and it changes text box. I only want to be able to put the values X, x, E, e, / My current jQuery code is

$('.today').keyup(function(e) {
  var self = $(this);
  var currentInput = self.data('number');
  var next = $(currentInput + 1);
  var previous = $(currentInput - 1);
  var keyCode = e.keyCode || e.which;
  var num = self.data('number') + 1;
  var nom = self.data('number') - 1;
  if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
    $('input.today[data-number="' + num +'"]').focus()
  else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
    $('input.today[data-number="' + nom +'"]').focus();
  else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
    $('input.today[data-number="' + num +'"]').focus();
  }
});

I only want the focused box to move if the key up is one of these: X, x, E, e, /, UP, DOWN, LEFT, RIGHT. And if the values are not X, x, E, e, / then to not write in the box

有帮助吗?

解决方案

This might help:

$('.today').keyup(function(e) {
  if(~[38, 39, 40, ...].indexOf(e.keyCode || e.which)) {
    e.preventDefault();
    return;
  }
  ...
}

The key there being the call to e.preventDefault().

You also have of the element the keyup event originated in as e.target.

HTH

其他提示

You can examine the key that was pressed to determine how the event should proceed. If you don't want text to appear on certain key presses, then you can either return false from the handler, or call e.preventDefault():

if ($.inArray(e.keyCode, [69, 88, 191]) === -1) { // e, x, / respectively
    e.preventDefault(); // don't print the character
}

You can get a list of the JavaScript keycodes here: Key Codes.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top