11

I have been trying to get this to work but I don't know what's going on, the code I have:

$('#buscar-producto').on('keydown', function(e){
    console.log('hello');
    console.log(e.keyCode);
});

It works on computers, but not on mobile..

EDIT: I need to get the keyCode when a key is pressed...

jhpratt
  • 6,841
  • 16
  • 40
  • 50
Aarón Gutiérrez
  • 1,400
  • 3
  • 16
  • 41

2 Answers2

12

keydown should work, but you could use the input event which seems to have undesired effects on Android mobile...
To get the code of the pressed key use the jQuery's normalized Event.which

Android Chrome tested:

Using input Event (e.which gives always 0 so it seems like a bug on android devices)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('input', function(e){
    var key = e.which || this.value.substr(-1).charCodeAt(0);
    alert( key )
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Using keydown (works as expected)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('keydown', function(e){
    alert( e.which );
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • I missed something in my question, could you re-read it please? :) – Aarón Gutiérrez Nov 24 '17 at 18:30
  • 1
    Use `input` as Roko mentioned and use `event.which` to get the keycode. See more at : https://api.jquery.com/event.which/ – bamtheboozle Nov 24 '17 at 18:34
  • 8
    keydown is now broken. Running this page on mobile with Desktop Mode so that snippet is available always gives 229 no matter what is pressed. On desktop, the correct character code comes up. Does anyone know what is causing this or what the fix is? – Niall Murphy Jun 13 '19 at 10:50
0

You can try event.key, event.keyCode, event.which.

If above all not working then you can try event.target.value.splice(-1)