Prevent entry of keyCode = 222 and keyCode = 186

2

I'm restricting the entry of certain characters to input type="text" , I need only numbers can be entered, I have almost ready but the only problem is that I can not prevent the characters of the keyCode keys == 222 and 186 they are entered, they are the ones that in the Spanish keyboard type the characters 'and' respectively.

The code:

$("#myInput").keydown(function(e){
  if (((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) && ((e.keyCode < 13 || e.keyCode > 13) && (e.keyCode < 8 || e.keyCode > 9))) && ((e.keyCode < 37 || e.keyCode > 37) && (e.keyCode < 39 || e.keyCode > 39)) || e.keyCode == 222 || e.keyCode == 186) {
    e.preventDefault();
  }

If they run the cursor to the right, in the final part of the if I am trying to restrict the keyCodes 222 and 186, but it does not work, I have nodded too much in that if , but I do not succeed.

Any suggestions on how to prevent the characters of those keys from being entered?

By the way, I know that there is input type="number" but for this specific project, it does not work for me.

EDIT

I just noticed that those keys if you press them once, they do not launch the character, but if you press them twice, they will throw the '' or '' character like this, twice. Then I deduce that it is a problem with the keydown, if so, what could I use without losing the functionality I already have?

  

PS: besides passing numbers, I also let pass the intro, the tab, backspace, left and right arrows because I need them.

    
asked by Roberto Sepúlveda Bravo 06.11.2016 в 00:01
source

1 answer

2

Intercept Spanish accents

The problem is that these keys are interpreted as accents, when pressed twice the keypress sends it as a key but the keydown does not detect it (tested in Chrome with Win10). To capture those keys you have to combine the keydown and keypress events. You have to capture the keys in both events

Example

Putting this in a file.html can be proved, in the first input you have to type, in the second you can see the codes, which do not match between keypress and keydown:

<input id=uno>
<input id=dos>
<script>
function stopNonNum(e){
  dos.value=e.keyCode+'/'+e.shiftKey;
  if(((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) 
      && ((e.keyCode < 13 || e.keyCode > 13) && (e.keyCode < 8 || e.keyCode > 9))) 
      && ((e.keyCode < 37 || e.keyCode > 37)) || e.keyCode == 222 || e.keyCode == 186 || e.keyCode == 96) 
  {
    dos.value=dos.value+'-';
    e.preventDefault();
  }else{
    dos.value=dos.value+'+';
  }
}
uno.onkeydown=stopNonNum;  
uno.onkeypress=stopNonNum;  
</script>
    
answered by 06.11.2016 / 00:28
source