Jayakumar Jayakumar - 12 days ago 5
HTML Question

How to disable typing special characters only not up, down, left and right keys?

I need enable 0 to 9 also up, down, left, right, delete, tab, home, end and etc like (alt, ctrl)
Need Chrome and Firefox browsers

$('.commonNumber').keypress(function(event){
var nbr = event.charCode ? event.charCode : event.keyCode;
// Numbers 8 -> Backspace 9-> Tab
if ((nbr >= 48 && nbr <= 57) || nbr == 8 || nbr == 9 || nbr == 37 || nbr == 38 || nbr == 46 || nbr == 39 || nbr == 40){
return true;
} else {
return false;
}


I enable 37, 38, 39,40,46 this codes are left, up, right, down areo and delete button keys but this keys are also %&('. keys using the same code. so this keys are enabled
});

Answer

When those other keys are pressed, the shift key will also be pressed. You can tell if the shift key is pressed by checking event.shiftKey.

$('.commonNumber').keypress(function(event) {
  var key = event.which,
      shift = event.shiftKey;

  return !shift
      && (
          (key >= 48 && key <= 57)
          || key == 8
          || key == 9
          || key == 37
          || key == 38
          || key == 6
          || key == 39
          || key == 40
      );
});

jsfiddle

Comments