Question

I have created a simple code to handle keypress event:

var counter = 0;        
$('input').on('keypress', function () {
    $('div').text('key pressed ' + ++counter);
});

JSFiddle.

But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+). What could be the issue?

Was it helpful?

Solution

Try keyup will help you

var counter = 0;        
$('input').on('keyup', function () {
    $('div').text('key up ' + ++counter);
});

OTHER TIPS

I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.

$(document).ready(function() {
  var pattForZip = /[0-9]/;
  $('#id').on('keypress input', function(event) {
    if(event.type == "keypress") {
      if(pattForZip.test(event.key)) {
        return true;
      }
      return false;
    }
    if(event.type == 'input') {
      var bufferValue = $(this).val().replace(/\D/g,'');
      $(this).val(bufferValue);
    }
  })
})

Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.

Eg:

function getKeyCode(str) {
  return str && str.charCodeAt(0);    
}
function keyUp(){
 var keyCode = getKeyCode("1"); 
}

Use jQuery's input event, like this:

$( 'input' ).on( 'input', function() {
    ...
} );

With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/

I think it is bad idea to use other events in place of 'keypress'. What you need to do is just include a jQuery file into your project. A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.

You can download it from : https://jquerymobile.com/download/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top