Pregunta

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

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top