How to capture the onscreen keyboard 'keydown' and 'keyup' events for touch devices

心不动则不痛 提交于 2019-11-28 10:52:19

Have you tried using key press instead of key down

$("#id").keypress(function() {

});

Updated :

Due to android problems I now normally wrap my checks like this

if ($.browser.mozilla) {
    $("#id").keypress (keyPress);
} else {
    $("#id").keydown (keyPress);
}

function keyPress(e){
    doSomething;
}

One way to solve this is by using setInterval when keyup or keydown events are not detected.

var keyUpFired = false;
$('#input').on('keyup',function() {
    keyUpFired = true;
    // do something
});
if( keyUpFired === false) {
    setInterval(function() {
        if($('#input').val().length>0) {
        // do something         
        }
    },100); 
}   

Here is a small example using Materialize in order to test in touch devices.

$(document).ready(function() {
var keyUpFired = false;
$('#input').on('keyup',function() {
keyUpFired = true;
if ($('#input').get(0).checkValidity() === true) {
$('label[for="input"]').attr('data-success','Custom Success Message: You typed...'+$(this).val());
} else {
$('label[for="input"]').attr('data-error','Custom Error Message: Username too small');	         
}
validate_field($('#input')); 
});
if(	keyUpFired == false) {
setInterval(function() {
if($('#input').val().length>0) {
if ($('#input').get(0).checkValidity() !== false) {
$('label[for="input"]').attr('data-success','Custom Success Message: You typed...'+$('#input').val());
} else {
$('label[for="input"]').attr('data-error','Custom Error Message: Username too small');	         
}
validate_field($('#input')); 	
}
},100);	
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css" rel="stylesheet"/>
 <div class="row">
    <form class="col s12">
      <div class="row">
        <div class="input-field col s12">
          <input placeholder="5-20 characters..." id="input" pattern=".{5,20}" type="text" class="validate">
          <label for="input" data-error="wrong" data-success="right">Username</label>
        </div>
      </div>
    </form>
  </div>
Paul Keane

The last answer on this page works: How can I get jquery .val() AFTER keypress event? -

Basically discard the "keyup" and change to "input", something like: $(document).delegate('#q', 'input', function(e) { etc }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!